indiegamedev

Unity3D Tutorials – Multiplayer – Latency Compensating Methods

Unity3D Tutorials – Multiplayer – Latency Compensating Methods

First see my previous tutorial about multiplayer basics at:
http://www.lucedigitale.com/blog/unity3d-tutorials-multiplayer-introduction/

What is LAG?

In online gaming, LAG is a noticeable delay between the action of players and the reaction of the server. Although LAG may be caused by high latency, it may also occur due to insufficient processing power in the client and/or server.

The tolerance for lag depends heavily on the type of game. For instance, a strategy game or a turn-based game with a low pace may have a high threshold or even be mostly unaffected by high delays, whereas a twitch gameplay game such as a first-person shooter with a considerably higher pace may require significantly lower delay to be able to provide satisfying gameplay.

LAG Compensation

First, to follow this lesson you need to see my tutorial about Multiplayer Introduction here:

http://www.lucedigitale.com/blog/unity3d-tutorials-multiplayer-introduction/

In the previous lesson you will notice a small delay between the input and the actual movement, this is because the position is updated after the new data is received. All we can do is predict what is going to happen based on the old data.

One method to predict the next position is by taking the velocity into account. A more accurate end position can be calculated by adding the velocity multiplied by the delay.

Unity3D – Our own synchronization method

MAIN TOP MENU> Edit> Project Settings > Network> Send Rate: 15
The standard settings in Unity3D is that a package is being tried to send 15 times per second, but our eyes are faster than 15 fps and we will see the LAG!
It is not a good practice use a greater value than 15, because we have to optimized the data will send thought the network.

The previous setup was:
Project> Cube (our player prefab)> Inspector> Network View> Observed: Transform

The new setup is:
Project> Cube (our player prefab)> Inspector> Network View> Observed: DRAG AND DROP here ‘Movement (Script)’ component
We will send thought the network our Movement.js to write our own synchronization method.

Movement.js


#pragma strict
 
function Start () {
 
}// END Start()
 
function Update () {
 
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 
 // Solo il server, cioè quello che parte per primo potrà spostare il cubo
 // Object instanted by me
 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	} else {
	enabled = false;
	}
}// END Update()

// We can write our own synchronization method START ############################
// This function is automatically called every time it either sends or receives data.
// By using stream.Serialize() the variable will be serialized and received by other clients.
function OnSerializeNetworkView(stream: BitStream, info: NetworkMessageInfo)
{
    var syncPosition : Vector3 = Vector3.zero; // management of position of rigid body
    if (stream.isWriting)
    {
        syncPosition = rigidbody.position; 
        stream.Serialize(syncPosition);
    }
    else
    {
        stream.Serialize(syncPosition);
        rigidbody.position = syncPosition;
    }
}
// We can write our own synchronization method END ###############################

Unity3D – Interpolation

To smooth the transition from the old to the new data values and fix these latency issues, interpolation can be used.

In computer animation, interpolation is inbetweening, or filling in frames between the key frames. It typically calculates the in between frames through use of (usually) piecewise polynomial interpolation to draw images semi-automatically.

We will interpolate between the current position and the new position received after synchronization.

Movement.js


#pragma strict
 
function Start () {
 
}// END Start()
 
function Update () {
 
 // User Input Control START ---------------------------------------------------
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 
 // Solo il server, cioè quello che parte per primo potrà spostare il cubo
 // Object instanted by me
 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	} else {
		SyncedMovement();
	}	
 // User Input Control END -----------------------------------------------------	
	
}// END Update()

// We can write our own synchronization method START ############################

private var lastSynchronizationTime: float = 0f;
private var syncDelay: float = 0f; // Delay between Updates
private var syncTime: float = 0f;
private var syncStartPosition: Vector3 = Vector3.zero; // Current Position
private var syncEndPosition: Vector3 = Vector3.zero; // New Position
 
function SyncedMovement ()
{
    syncTime += Time.deltaTime;
    rigidbody.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}// END SyncedMovement()
   
// This function is automatically called every time it either sends or receives data.
// By using stream.Serialize() the variable will be serialized and received by other clients. 
function OnSerializeNetworkView(stream: BitStream , info: NetworkMessageInfo )
{
    var syncPosition: Vector3 = Vector3.zero;
    // The BitStream class represents seralized variables, packed into a stream.
    // if the BitStream is currently being read= TRUE
    // se il flusso di dati sta per essere scritto la posizione è quella ricevuta
    if (stream.isWriting) 
    {
        syncPosition = rigidbody.position;
        stream.Serialize(syncPosition);
    }
    // se il flusso NON stà per essere scritto, interpola i dati INIZIO ---------
    else
    {
        stream.Serialize(syncPosition);
 
        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;
 
        syncStartPosition = rigidbody.position;
        syncEndPosition = syncPosition;
    }
    // se il flusso NON stà per essere scritto, interpola i dati FINE -----------
}

// We can write our own synchronization method END ###############################

Play and try, now the transitions look smooth! YEAH!

For italian people: come funziona?

1. Se il player è stato generato da me muovilo con GetAxis, altrimenti non posso muoverlo

...

 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));
...

2. altrimenti muovilo utilizzando l’interpolazione

...
function SyncedMovement ()
{
    syncTime += Time.deltaTime;
    rigidbody.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}// END SyncedMovement()
...

3. L’interpolazione viene attivata solamente nel momento in cui il flusso di dati non è in scrittura

...
else
    {
        stream.Serialize(syncPosition);
 
        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;
 
        syncStartPosition = rigidbody.position;
        syncEndPosition = syncPosition;
    }
...

Unity3D – Prediction

You will notice a small delay between the input and the actual movement. This is because the position is updated after the new data is received.
All we can do is predict what is going to happen based on the old data.

One method to predict the next position is by taking the velocity into account. A more accurate end position can be calculated by adding the velocity multiplied by the delay.

Movement.js


#pragma strict
 
function Start () {
 
}// END Start()
 
function Update () {
 
 // User Input Control START ---------------------------------------------------
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 
 // Solo il server, cioè quello che parte per primo potrà spostare il cubo
 // Object instanted by me
 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	} else {
		SyncedMovement();
	}	
 // User Input Control END -----------------------------------------------------	
	
}// END Update()

// We can write our own synchronization method START ############################

private var lastSynchronizationTime: float = 0f;
private var syncDelay: float = 0f; // Delay between Updates
private var syncTime: float = 0f;
private var syncStartPosition: Vector3 = Vector3.zero; // Current Position
private var syncEndPosition: Vector3 = Vector3.zero; // New Position
 
function SyncedMovement ()
{
    syncTime += Time.deltaTime;
    rigidbody.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}// END SyncedMovement()
   
// This function is automatically called every time it either sends or receives data.
// By using stream.Serialize() the variable will be serialized and received by other clients. 
function OnSerializeNetworkView(stream: BitStream , info: NetworkMessageInfo )
{
    var syncPosition: Vector3 = Vector3.zero;
    var syncVelocity: Vector3 = Vector3.zero;
    // The BitStream class represents seralized variables, packed into a stream.
    // if the BitStream is currently being read= TRUE
    // se il flusso di dati sta per essere scritto la posizione è quella ricevuta
    if (stream.isWriting) 
    {
        syncPosition = rigidbody.position;
        stream.Serialize(syncPosition);
        
        syncVelocity = rigidbody.velocity;
        stream.Serialize(syncVelocity);
    }
    // se il flusso NON stà per essere scritto, interpola i dati INIZIO ---------
    else
    {
        stream.Serialize(syncPosition);
        stream.Serialize(syncVelocity);
 
        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;
 
        syncEndPosition = syncPosition + syncVelocity * syncDelay;
        syncStartPosition = rigidbody.position;
    }
    // se il flusso NON stà per essere scritto, interpola i dati FINE -----------
}

// We can write our own synchronization method END ###############################

You will notice the transitions are still smooth and the latency between your input and the actual movement seem less.

My official website: http://www.lucedigitale.com

References:

– http://docs.unity3d.com/Manual/net-HighLevelOverview.html
– http://www.inetdaemon.com/tutorials/internet/ip/whatis_ip_network.shtml
– http://whatismyipaddress.com/nat
– http://vimeo.com/33996023#
– http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/

Extra resources:

– http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking
– http://developer.valvesoftware.com/wiki/Lag_Compensation
– http://developer.valvesoftware.com/wiki/Working_With_Prediction
– http://www.gamasutra.com/resource_guide/20020916/lambright_01.htm

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Tutorials – Multiplayer – Latency Compensating Methods

Unity3D – Tutorials – UI – Scroll Rect – Text

Unity3D – Tutorials – UI – Scroll Rect – Text

Inside a Scrool Rect you can scroll a text greater than the Scroll Rect Area.

Scrool Rect – Yes ScroolBars

0. MAIN TOP MENU> GameObject> UI> Canvas

1. MAIN TOP MENU> GameObject> UI> Text

2. MAIN TOP MENU> GameObject> Empty Object, rename it ScrollRectObj

3. Hierarchy> select ScrollRectObj> Inspector> ‘Add Component’
> Scroll Rect (Transform component will be authomatic removed)
> Image
> Mask

4. Parent as show below:

– Canvas
-> ScrollRectObj (child of Canvas)
->> Text (child of ScrollRectObj)

5. Setup size and position:

– Inspector> ScrollRectObj: Width= 100 Height= 100 Pos XYZ= 0,0,0

– Inspector> Text: Width= 100 Height= 400 Pos XYZ= 0,0,0

The Text is greater than ScrollRectObj and it will scroll from top to bottom

6. Setup ScrollRectObj

– Inspector> ScrollRectObj> Scroll Rect (Script)> Content, DRAG AND DROP from ‘Hierachy> Text’ here

7. Vertical Scroll Bar

a. Hierarchy> RMB over Canvas> UI> Scrollbar

– Canvas
-> ScrollRectObj (child of Canvas)
->> Text (child of ScrollRectObj)
-> Scrollbar (MUST BE CHILD OF CANVAS)

b. Hierarchy> select Scrollbar DRAG AND DROP Inspector> ScrollRectObj> Scroll Rect (Script)> Vertical Scrollbar

c. Inspector> ScrollBar> Rect Transform> Rotation Z=90
OR
c. Inspector> ScrollBar> Scrollbar (Script)> Direction> Top To Bottom

3. Play and enjoy!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Tutorials – UI – Scroll Rect – Text

Unity3D – Tutorials – UI – Responsive Button Setup

Unity3D – Tutorials – UI – Responsive Button Setup

This feature is avaiable for Unity3D 4.6 or above.

Create Objects

1. Open Unity3D and create:

– MAIN TOP MENU> GameObject> Camera, name it ‘Main Camera’
– MAIN TOP MENU> GameObject> UI> Canvas
– MAIN TOP MENU> GameObject> UI> Button, this will add an ‘EventSystem’ and Button will be child of Canvas

NOTICE: Canvas will be created inside Layer UI

NOTICE: In the Hierarchy there is:
– Canvas
-> Button (it is the child of Canvas)
->> Text (it is the child of Button)

Setup Viewports and Tools

2. 3D Viewport select orthographic X View
3. TOP LEFT> TOOLS> Canvas Manipulation icon
4. Game Viewport> 4:3

Setup Canvas

5. Hierarchy> Canvas> Inspector>

Canvas>
– Render Mode: ScreenSpace – Overlay (you will see the button over 3D scene)
– Pixel Perfect: check

Canvas Scaler>
– Ui Scale Mode> Scale with Screen Size
– Reference Resolution: 800×600 (Remember that Game Viewport is set at 4:3)
E’ solo una unità di riferimento, non sono pixel, ci baseremo su questo parametro per settare i parametri di Rect Transform
– Screen Match Mode: Match Width or Height

NOTE: Pixel Perfect means when displaying a 2D texture, each pixel in the texture is represented by only one pixel on the screen. When you want your 2D-displayed textures to look their best, this is often what is strived for.

Setup Button

6. Hierarchy> Button> Inspector>

Rect Transform>

– Width: 400 (Remember that Reference Resolution is 800×600)
– Height: 200 (Remember that Reference Resolution is 800×600)

WARNING: If you use ‘Scale XYZ’ the graphic will be stretched.

Center Alignement – No Stretch
Anchor Preset Button (the square icon on top left with a target): middle center
Anchors: Min X=0.5 Y=0.5 Max X=0.5 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: 0,0,0

Left Alignement – No Stretch
Anchor Preset Button (the square icon on top left with a target): middle center
Anchors: Min X=0.5 Y=0.5 Max X=0.5 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: -200,0,0 (Remember that Reference Resolution is 800×600 -> 800/2-400/2=200)

Right Alignement – No Stretch
Anchor Preset Button (the square icon on top left with a target): middle center
Anchors: Min X=0.5 Y=0.5 Max X=0.5 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: 200,0,0

Top Right Alignement – No Stretch
Anchor Preset Button (the square icon on top left with a target): middle center
Anchors: Min X=0.5 Y=0.5 Max X=0.5 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: 200,250,0

Top Left Alignement – No Stretch
Alignement icon (the square icon on top left with a target): middle center
Anchors: Min X=0.5 Y=0.5 Max X=0.5 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: -200,250,0

Center Alignement – Stretch Width
Anchor Preset Button (the square icon on top left with a target): middle stretch
Anchors: Min X=0 Y=0.5 Max X=1 Y=0.5 Pivot X=0.5 Y=0.5
PosXYZ: 0,0,0

Center Alignement – Stretch Height
Anchor Preset Button (the square icon on top left with a target): stretch center
Anchors: Min X=0.5 Y=0 Max X=0.5 Y=1 Pivot X=0.5 Y=0.5
PosXYZ: 0,0,0

Center Alignement – Stretch Width and Height
Anchor Preset Button (the square icon on top left with a target): stretch strech
Anchors: Min X=0 Y=0 Max X=1 Y=1 Pivot X=0.5 Y=0.5
PosXYZ: 0,0,0

Image (Script)> setup the appearance you like

Button (Script)> setup the appearance you like

Setup Button Text

7. Hiearchy> select Text (child of Button)> Inspector>

> Rect Transform

Pos XYX: to positioning text

Width, Height: to size the rectangle that contain the text

Anchors Preset Button: to setup anchors

Rotation: to rotate text

Scale: WARNING: using scale the graphic will be stretched! Use Text> Font Size instead, it is better.

> Text

Font: PAY ATTENTION you need include the font inside the project to Build the game or your font will be lost in the final executable build.

Font Size: to resize the text

No Overflow
Horizontal Overflow: Wrap
Vertical Overflow: Truncate

Yes Horizontal and Vertical Overflow
Horizontal Overflow: Overflow
Vertical Overflow: Overflow

8. Try resize Game Window… it will works great!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Tutorials – UI – Responsive Button Setup

Client-Server Communication Socket-Based in Videogames – Basic Concepts

Client-Server Communication Socket-Based in Videogames – Basic Concepts

What is a Client-Server Communication

Client-server is a request-response remote communication model that involves processes requesting services from other processes which offer these services via the network.
The processes offering services by executing certain tasks following remote process requests are known as servers. In general, the servers receive requests from remote processes, execute the tasks associated with these services, and dispatch responses back to the requesting entities. Example of services include database information retrieval and updates, file system access services, and dedicated user-application tasks.
The process that contact the servers and request them to perform services is known as Client

In general, Client processes manage user-interfaces, validate data entered by users, dispatch requests to servers, collect servers’ responses, and/or display the information received.

Client-Server Communication in Videogames

In the fantastic world of videogames development we find:

Client
It is the videogame, installed in your PC, Mobile Device or Web Player, generally:
– manage the user input
– manage local data as scores, lives etc…
– collect data from a database installed inside a Server and manage it inside the videogame

Server
It is the computer that stores (using for example MySQL) accounts, scores and others usefull datas for the gamer
If you play a MMORPG (Massive(ly) Multiplayer Online Role-Playing Game, you will see that the Server manages a lot af data and thousands of users in the same time.

Low Data Management

If you have to manage few users or only username and scores value, the server will not work hard, it is enough a communication like that:

Client (Videogame) -> PHP POST REQUEST -> Server with PHP+MySQL offers a service

High Data Management

You are in trouble, there are thousands of users that sends thousands of PHP POST in the same time.
Using the previus scheme we have:

Client1 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client2 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client3 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client4 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client5 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client6 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client7 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client8 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client9 (Videogame) -> PHP POST -> Server with PHP+MySQL offers a service
Client1000000 (Videogame) -> PHP POST REQUEST -> Server with PHP+MySQL offers a service …-> CRASH OF THE SYSTEM!!!

The solution are:

1. Use of SSD (Solid State Drive) instead ad traditional Hard Driver
2. Use of one or more dedicated servers, not sharing IP or low-end hosting solution admitted!
3. Use of Client-Server Communication Socket-Based

The Client-Server Communication Socket-Based is:

Client1 (Videogame) -> PHP POST -> | |
Client2 (Videogame) -> PHP POST -> | |
Client3 (Videogame) -> PHP POST -> | |
Client4 (Videogame) -> PHP POST -> | |
Client5 (Videogame) -> PHP POST -> | Socket manage REQUEST | -> Server with PHP+MySQL offers a service
Client6 (Videogame) -> PHP POST -> | (Multithreaded) |
Client7 (Videogame) -> PHP POST -> | |
Client8 (Videogame) -> PHP POST -> | |
Client9 (Videogame) -> PHP POST -> | |

With WebSockets you can transfer as much data as you like without incurring the overhead associated with traditional HTTP requests. Data is transferred through a WebSocket as messages, each of which consists of one or more frames containing the data you are sending (the payload).

To run a WebSocket you need a DEDICATED IP, no SHARED IP are allowed, because you will setup your own IP and listening ports.

A popular software to create a WebSocket is Node.js (http://nodejs.org/).

WebSoscket inside a SHARED IP

You can run Node.js in a shared host using CGI-Node (http://www.cgi-node.org/).
‘CGI-Node’ is a CGI adaptor for node.js that mimmicks the Node.js http library.

Low Latency Client-Server and Server-Client Connections

Around 2005, AJAX started to make the web feel more dynamic. Still, all HTTP communication was steered by the client, which required user interaction or periodic polling to load new data from the server.

One of the most common hacks to create the illusion of a server initiated connection is called long polling. With long polling, the client opens an HTTP connection to the server which keeps it open until sending response. Long polling and the other techniques work quite well. You use them every day in applications such as GMail chat.

However, all of these work-arounds share one problem: They carry the overhead of HTTP, which doesn’t make them well suited for low latency applications. Think multiplayer first person shooter games in the browser or any other online game with a realtime component.

The WebSocket (http://dev.w3.org/html5/websockets/) specification defines an API establishing “socket” connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time over a single TCP channel.

WebSocket give you a bidirectional communication technology for web apps for:
IE 10 or over
Firefox 33 or over
Chrome 31 or over
Safari 7.1 or over
Opera 26 or over
iOS Safari 7.1 or over
Android Browser 4.4 or over
Chrome for Android 39 or over

What it means single TCP Channel?

The Transmission Control Protocol (TCP) is one of the core protocols of the Internet protocol suite (IP), and is so common that the entire suite is often called TCP/IP.

IP works by exchanging pieces of information called packets. A packet is a sequence of bytes and consists of a header followed by a body. The header describes the packet’s source, destination and control information. The body contains the data IP is transmitting. The size of one IP packet is 65535 bytes (63.99902 Kbyte or 0.0625 Mbyte).

Due to network congestion, traffic load balancing, or other unpredictable network behavior, IP packets can be lost, duplicated, or delivered out of order. TCP detects these problems, requests retransmission of lost data, rearranges out-of-order data, and even helps minimize network congestion to reduce the occurrence of the other problems.

TCP is utilized extensively by many of the Internet’s most popular applications, including the World Wide Web (WWW), E-mail, File Transfer Protocol, Secure Shell, peer-to-peer file sharing, and some streaming media applications.
TCP is optimized for accurate delivery rather than timely delivery, and therefore, TCP sometimes incurs relatively long delays (on the order of seconds) while waiting for out-of-order messages or retransmissions of lost messages. It is not particularly suitable for real-time applications such as Voice over IP. For such applications, protocols like the Real-time Transport Protocol (RTP) running over the User Datagram Protocol (UDP) are usually recommended instead.

Ready to use solutions

Setup a server is very expensive, sometimes the budget and the time we can spend to develop is not enought to do that.
In the market there are some ready to use platforms to build multiplayer games.

Photon Cloud

https://www.exitgames.com

Photon Cloud is available globally to guarantee low latency and shortest round-trip times for your multiplayer games worldwide.
Distributed worldwide Photon Cloud scales seamless and automatically even for tens of thousands of concurrent users.

Customers: from indie to AAA

Support:

– Unity3D (check Unity3D Asset Store also)
– iOS
– Android
– Win8
– Unreal4
– Cocos
– HTML5
– Flash
– Marmalade
– Corona

– Realtime Multiplayer
– Turn Based Games
– Chat

App Warp

http://appwarp.shephertz.com/

Powerful, yet simple to use cloud platform for massively multiplayer realtime games

Customers: from indie to AAA

Support:

– Unity3D
– iOS
– Android
– Win8
– Unreal4
– Cocos
– HTML5
– Flash
– Marmalade
– Corona
– J2me SDK
– andengine
– Starlink SDK
– Fixel SDK
– Sencha SDK

Game Cloud

http://game-cloud.org/

Using our advanced technology we reduce the traffic to the player allowing large number of players to connect even on slow (mobile) networks without lagging

Support:

– Unity3D (Build for Unity3D integrated into Unity Editor Tools)
– Win 8
– Android
– Mac OS
– Linux
– Playstation
– XBox 360
– Wii
– iOS
– Browsers

Gamooga

http://www.gamooga.com/

State-of-art realtime backend for your apps/games that guarantees under 1ms response time. None of our competitiors can beat us here!

Support:

– Unity3D
– HTML5
– iOS
– Android
– Falsh
– Marmalade

Gamespark

http://www.gamesparks.com/

GameSparks ensures you keep your costs to a minimum whether they be intial set-up or recurring fees

Support:

– Unity3D
– Unreal 4
– iOS
– Android
– Falsh
– Marmalade

My official website: http://www.lucedigitale.com

References:

– Server Side Score
http://www.lucedigitale.com/blog/unity-3d-server-side-highscores-js-programming/

– Advanced Network Programming – Principles and Techniques (By Bogdan Ciubotaru, Gabriel-Miro Muntean)

– http://www.html5rocks.com/en/tutorials/websockets/basics/ (By Malte Ubl and Eiji Kitamura)

– http://caniuse.com/#feat=websockets

By |Video Games Development|Commenti disabilitati su Client-Server Communication Socket-Based in Videogames – Basic Concepts

Unity3D Tutorials – Multiplayer Introduction

Unity3D Tutorials – Multiplayer Introduction

In this article I discuss how to create a simple multiplayer game using a Windows Home Network and 2 PC.
First we need some basic concept about Network and Networking.

Network Computing – Basic Concepts

A Network of PC
To create a network we need 2 or more PC connected with a Router using a LAN cable.

The simplest network is:

PC1 <-> Router <-> PC2

The router is a networking device that forwards data packets between computer networks.

Network Software Setup

If you use Windows7 is very simple setup a Home Network, go to Start button> ‘Control Panel’ and typing homegroup in the search box, and then clicking HomeGroup. After that Windows7 assigns a dynamic IP adress to every PC connected on the network.

An IP adress is a adress that uniquely identifies that individual host maschine inside the network.
An IP adress can be:
– Dynamic, the router assigns automatically a different IP number to every PC connected
– Static, you can manually assign the IP number to your PC

The final resul will be:

PC1(IP 192.168.1.10) <-> Router <-> PC2(IP 192.168.1.11)

IP Private – IP Public & NAT

The most common form of network translation involves a large private network using addresses in a private range (10.0.0.0 to 10.255.255.255, 172.16.0.0 to 172.31.255.255, or 192.168.0 0 to 192.168.255.255). The private addressing scheme works well for computers that only have to access resources inside the network, like workstations needing access to file servers and printers. Routers inside the private network can route traffic between private addresses with no trouble.

However, to access resources outside the network, like the Internet, these computers have to have a public address in order for responses to their requests to return to them. This is where NAT (Network Address Translation) comes into play.
A workstation inside a network makes a request to a computer on the Internet. Routers within the network recognize that the request is not for a resource inside the network, so they send the request to the firewall. The firewall sees the request from the computer with the internal IP. It then makes the same request to the Internet using its own public address, and returns the response from the Internet resource to the computer inside the private network. From the perspective of the resource on the Internet, it is sending information to the address of the firewall. From the perspective of the workstation, it appears that communication is directly with the site on the Internet. When NAT is used in this way, all users inside the private network access the Internet have the same public IP address when they use the Internet. That means only one public addresses is needed for hundreds or even thousands of users.

The scheme is:

PC1(IP Private) | <->
PC2(IP Private) | <->
PC2(IP Private) | <-> Router <-> Firewall (NAT) assign one IP Public <-> Internet
PC2(IP Private) | <->
PC2(IP Private) | <->

Ports

In computer networking, a port is an application-specific or process-specific software construct serving as a communications endpoint in a computer’s host operating system. The purpose of ports is to uniquely identify different applications or processes running on a single computer and thereby enable them to share a single physical connection to a packet-switched network like the Internet. In the context of the Internet Protocol, a port is associated with an IP address of the host, as well as the type of protocol used for communication.

An example for the use of ports is the Internet mail system. A server used for sending and receiving email generally needs two services. The first service is used to transport email to and from other servers. This is accomplished with the Simple Mail Transfer Protocol (SMTP). The SMTP service application usually listens on TCP port 25 for incoming requests. The second service is usually either the Post Office Protocol (POP) or the Internet Message Access Protocol (IMAP) which is used by e-mail client applications on user’s personal computers to fetch (recuperare) email messages from the server. The POP service listens on TCP port number 110.

The well-known ports (also known as system ports) are those from 0 through 1023.

Very popular are:

20 & 21: File Transfer Protocol (FTP)
22: Secure Shell (SSH)
23: Telnet remote login service
25: Simple Mail Transfer Protocol (SMTP)
53: Domain Name System (DNS) service
80: Hypertext Transfer Protocol (HTTP) used in the World Wide Web
110: Post Office Protocol (POP3)
119: Network News Transfer Protocol (NNTP)
143: Internet Message Access Protocol (IMAP)
161: Simple Network Management Protocol (SNMP)
194: Internet Relay Chat (IRC)
443: HTTP Secure (HTTPS)
465: SMTP Secure (SMTPS)

The registered ports are those from 1024 through 49151.

The scheme is:

External application <-> Router IP/Port <-> destination in network IP/Port

Port 25001 is default port for Unity3D game engine networking, UDP protocol.

Game Network approches

There are two common and proven approaches to structuring a network game which are known as Authoritative Server and Non-Authoritative Server.

The authoritative server approach requires the server to perform all world simulation, application of game rules and processing of input from the player clients.

A non-authoritative server does not control the outcome of every user input. The clients themselves process user input and game logic locally, then send the result of any determined actions to the server. The server then synchronizes all actions with the world state. This is easier to implement from a design perspective, as the server really just relays messages between the clients and does no extra processing beyond what the clients do.

Methods of Network Communication

How clients and servers can talk to each other?

There are two relevant methods: Remote Procedure Calls and State Synchronization. It is not uncommon to use both methods at different points in any particular game.

Remote Procedure Calls (RPCs) are used to invoke functions on other computers across the network, although the “network” can also mean the message channel between the client and server when they are both running on the same computer. Clients can send RPCs to the server, and the server can send RPCs to one or more clients. Most commonly, they are used for actions that happen infrequently. For example, if a client flips a switch to open a door, it can send an RPC to the server telling it that the door has been opened. The server can then send another RPC to all clients, invoking their local functions to open that same door. They are used for managing and executing individual events.

State Synchronization is used to share data that is constantly changing. The best example of this would be a player’s position in an action game. The player is always moving, running around, jumping, etc. All the other players on the network, even the ones that are not controlling this player locally, need to know where he is and what he is doing. By constantly relaying data about this player’s position, the game can accurately represent that position to the other players.

Minimizing Network Bandwidth

When working with State Synchronization across multiple clients, you don’t necessarily need to synchronize every single detail in order to make objects appear synchronized. For example, when synchronizing a character avatar you only need to send its position and rotation between clients.

For example, you know that assets like textures and meshes exist on all installations and they usually don’t change, so they will never have to be synchronized.

Bear in mind that you can use a single RPC call with a level name to make all clients load the entire specified level and add their own networked elements automatically. Structuring your game to make each client as self-sufficient as possible will result in reduced bandwidth.

Server Physical Location

The physical location and performance of the server itself can greatly affect the playability of a game running on it. Clients which are located a continent away from the server may experience a great deal of lag.

Unity 3D – State Synchronization

For this Unity3D tutorial I am going to work with a simple Home Network created with Windows7.

1. Create a scene with:
– Main Camera
– Cube, Pos XYZ 0,0.5,0 – Scale xYZ 1,1,1
– Plane, Pos XYZ 0,0,0 – Scale xYZ 10,10,10
– Directional Light
– Empty Object, name it ‘NetworkController’

2. Attach to the Cube, Movement.js


#pragma strict
 
function Start () {
 
}
 
function Update () {
 
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
}

3. Attach to NetworkController, NetworkManagerScript.js


#pragma strict

var btnX:float; // Buttons Setup
var btnY:float;
var btnW:float;
var btnH:float;

function Start () {
	btnX = Screen.width * 0.05; // Buttons Setup
	btnY = Screen.width * 0.05; // Dimension based on Screen.width
	btnW = Screen.width * 0.2;
	btnH = Screen.width * 0.2;

}

function startServer() {
        // This machine will be the sever
        // Initialize the server, number of allowed connection 32, listenport 25001, NOT have a public IP Adress
	Network.InitializeServer(32,25001, !Network.HavePublicAddress);
}

// Called when Network.InitializeServer was invoked and has completed.
function OnServerInitialized() {
	Debug.Log("Server Initialized");
}

function OnGUI() {
	if(GUI.Button(Rect(btnX, btnY,btnW,btnH),"Start Server")){
	Debug.Log("Starting Server");
	startServer();
	}
	
	if(GUI.Button(Rect(btnX, btnY*1.2+btnH,btnW,btnH),"Refresh Hosts")){
	Debug.Log("Refreshing");
	
	}
}

function Update () {

}

Play, in the console you will receive the message ‘Sever Initialized’
Good! Now my Unity3D application is the Server.

Next, improve NetworkManagerScript.js


#pragma strict

var gameName: String = "MyFirstNetGame"; 

private var btnX:float; // Buttons Setup
private var btnY:float;
private var btnW:float;
private var btnH:float;

function Start () {
	btnX = Screen.width * 0.05; // Buttons Setup
	btnY = Screen.width * 0.05; // Dimension based on Screen.width
	btnW = Screen.width * 0.2;
	btnH = Screen.width * 0.2;

}

function startServer() {
        // This machine will be the Server
        // Initialize the server, number of allowed connection 32, listenport 25001, NOT have a public IP Adress
	Network.InitializeServer(32,25001, !Network.HavePublicAddress);
	
	// Register this server on the master server 
	// The Master Server is a meeting place that puts game instances in touch with the player clients who want to connect to them. 
	// Each individual running game instance provides a Game Type to the Master Server
	//(gameTypeName: string, gameName: string, comment: string = "")
	MasterServer.RegisterHost(gameName, "My Game Name", "This is a comment");
}

// Called when Network.InitializeServer was invoked and has completed.
function OnServerInitialized() {
	Debug.Log("Server Initialized");
}

// Called on clients or servers when reporting events from the MasterServer
function OnMasterServerEvent(mse:MasterServerEvent){
        // check if registration is ok
	if (mse == MasterServerEvent.RegistrationSucceeded){
	Debug.Log("Registrered Server!");
	}
}

function OnGUI() {
	if(GUI.Button(Rect(btnX, btnY,btnW,btnH),"Start Server")){
	Debug.Log("Starting Server");
	startServer();
	}
	
	if(GUI.Button(Rect(btnX, btnY*1.2+btnH,btnW,btnH),"Refresh Hosts")){
	Debug.Log("Refreshing");
	
	}
}

function Update () {

}

Play it, you will get in console “Server Initialized -> Registrered Server!”

For italian people: come funziona?

1. Network.InitializeServer(32,25001, !Network.HavePublicAddress);
Inizializza l’applicazione Server attraverso il network, identifica IP, la porta, il numero massimo di connessioni ammesse.

2. MasterServer.RegisterHost(gameName, “My Game Name”, “This is a comment”);
Il MasterServer è il punto di incontro tra i vari Clients, quindi registriamo presso il MasterServer l’applicazione con un identificativo di tipo, nome e un commento.

Next, improve NetworkManagerScript.js


#pragma strict

var gameName: String = "MyFirstNetGame"; 
private var refreshing: boolean;
private var hostData: HostData[];

private var btnX:float; // Buttons Setup
private var btnY:float;
private var btnW:float;
private var btnH:float;

function Start () {
	btnX = Screen.width * 0.05; // Buttons Setup
	btnY = Screen.width * 0.05; // Dimension based on Screen.width
	btnW = Screen.width * 0.2;
	btnH = Screen.width * 0.2;

}

function startServer() {
    // This machine will be the Server
    // Initialize the server, number of allowed connection 32, listenport 25001, NOT have a public IP Adress
	Network.InitializeServer(32,25001, !Network.HavePublicAddress);
	
	// Register this server on the master server 
	// The Master Server is a meeting place that puts game instances in touch with the player clients who want to connect to them. 
	// Each individual running game instance provides a Game Type to the Master Server
	//(gameTypeName: string, gameName: string, comment: string = "")
	MasterServer.RegisterHost(gameName, "My Game Name", "This is a comment");
} // END startServer

function refreshHostList() {
    // check the number of hosts registered in MasterServer
    // controlla il numero di applicazioni registrate in MasterServer con 'gameName'
    // la registrazione al MasterServer può richiedere dai 3 ai 6 secondi
	MasterServer.RequestHostList(gameName);
	refreshing = true;
} // END refreshHostList

// Called when Network.InitializeServer was invoked and has completed.
function OnServerInitialized() {
	Debug.Log("Server Initialized");
}// END OnServerInitialized

// Called on clients or servers when reporting events from the MasterServer
function OnMasterServerEvent(mse:MasterServerEvent){
    // check if registration is ok
	if (mse == MasterServerEvent.RegistrationSucceeded){
	Debug.Log("Registrated Server!");
	}
}

// GUI Graphic User Interface
function OnGUI() {
//  if your peer type is NOT client AND is NOT server, cioè se non è già connnesso
// questo if fa scomparire i bottoni una volta cliccato su 'Start Server'
if (!Network.isClient && !Network.isServer){
	if(GUI.Button(Rect(btnX, btnY,btnW,btnH),"Start Server")){
	Debug.Log("Starting Server");
	startServer();
	}
	
	if(GUI.Button(Rect(btnX, btnY*1.2+btnH,btnW,btnH),"Refresh Hosts")){
	Debug.Log("Refreshing");
	refreshHostList();
	}
	
	// se esistono dei gameName registrati su MasterServer
	if (hostData){
		// visualizza un array di bottoni con tutti i gameName registrati come MasterServer
		for(var i:int = 0; i<hostData.length; i++){
		    // se viene premuto il bottone
			if (GUI.Button(Rect(btnX*1.5 + btnW, btnY*1.2 + (btnH * i),btnW*3, btnH*0.5), hostData[i].gameName)){
				// Connect to the specified host (ip or domain name) and server port
				// Example: Network.Connect("127.0.0.1", 25000)
				Network.Connect(hostData[i]);
			}
		}
	}
}	
}// END OnGUI

function Update () {
    // se refreshing è true, cioè ho cliccato sul bottone 'Refresh Hosts'
	if (refreshing) {
		// se c'è almeno una registrazione
		if (MasterServer.PollHostList().Length > 0)  {
		// disabilita il refreshing per evitare che continui ad eseguirlo ad ogni ciclo Update
		refreshing = false;
		Debug.Log(MasterServer.PollHostList().Length);
		// array con tutte le registrazioni al MasterServer
		hostData = MasterServer.PollHostList();
		}	
	}// END Refreshing

}// END Update

For italia people: come funziona?

1. Inseriamo in un array – private var hostData: HostData[] – tutte le connessioni registrare nel MasterServer
2. Con un ciclo for le visualizzo utilizzando una grafica composta di bottoni – (var i:int = 0; iTestBuild.exe

1. MAIN TOP MENU> Edit> Project Settings> Player> Inspector> Settings for PC Mac LinuX Standalone> Run in Background: check

L’applicazione deve essere attiva in background perchè deve continuare ad inviare dati al MasterServer anche quando non lo stiamo utilizzando.
Se così non fosse ogni volta che usciamo dal gioco, lasciandolo attivo nella barra di windows, la connessione con il MasterServer andrebbe persa.
Con l’applicazione settata per funzionare in background invece posso lasciare il gioco attivo, utilizzare un’altra applicazione e tornare al gioco senza dover di nuovo effettuare la procedura di registrazione al MasterServer.

2. MAIN TOP MENU> File> Buil Settings…> PC Mac Linux Standalone> Build, TestBuild.exe

a. Run the standalone build, click ‘Start Server’, the buttons will disapper
b. Play inside Unity3D the Project> click ‘Refresh Hostst’, you will see the registered host, yeah it works!

For italian people: come funziona?
a. Creo un buil stand alone e l’avvio, questa crea il MasterServer e si registra presso il MasterServer come client
b. Avvio da Unity3D il progetto, cliccando su’Refresh Hosts’ osservo che effettivamente la build standalone funziona ed è reistrata presso il MasterServer.
c. Posso provare a chiedere TestBuild.exe e riavviare il progetto su Unity3D, cliccare su ‘Refresh Hosts’, nessun applicazione risulterà registrata a MasterServer

Network View Component

1. Hierarchy> select Cube (our player)> Inspector > ‘Add Component’> Miscellaneous> Network View:

– State Syncronization: Reliable Delta Compressed
The difference between the last state and the current state will be sent, if nothing has changed nothing will be sent.

– Observed: Cube(Transform)
The Component data that will be sent across the network

‘Network Views’ are the gateway to creating networked multiplayer games in Unity.

New TestBuild.exe

1. Save the scene and the project
2. Build and run the standalone exe, press ‘Start Server’, all buttons disappear.
3. Play inside Unity3D the Project> click ‘Refresh Hosts’, the button ‘Tutorial Game Name’ appears, press it to starl this client, all buttons disappear.
4. Jump to standalone exe, move the Cube using the arrow key. In the Unity Game window you will see the cube goes all around!

For italian people: come funziona?

1. Primo eseguibile: premendo ‘Start Server’ questa applicazione funzionerà da Server e in più si registrerà come client
2. Secondo eseguibile: facendo un refresh degli hosts si visualizza il Server attualmente registrato (il primo eseguibile)
3. Secondo eseguibile: facendo click sul nome del Server si registra il secondo eseguibile come client
Se si tenta di far partire il server dal secondo eseguibile si riceverà la risposta che il server è già stato avviato.

The Player is mine!

A this point in time both players can move the same cube… mmm… it sounds strange…

Let’s take a look to the new Movement.js


#pragma strict
 
function Start () {
 
}// END Start()
 
function Update () {
 
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 
 // Solo il server, cioè quello che parte per primo potrà spostare il cubo
 // Object instanted by me
 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	}
}// END Update()

For italian people: come funziona?
1. Il primo eseguibile che viene avviato genera l’oggetto e diventa di sua proprietà – networkView.isMine –
2. Solo se l’oggetto è di mia proprietà puoi muoverlo
3. Il secondo eseguibile può solo assistere al movimento del cubo senza poter inviare dei comandi

Spawn Player

1. Add to NetworkManagerScript.js the code:


...

var playerPrefab: GameObject;
var spawnObject: Transform;

...

function spawnPlayer() {
	Network.Instantiate(playerPrefab, spawnObject.position, Quaternion.identity, 0);
}

// Called when Network.InitializeServer was invoked and has completed.
function OnServerInitialized() {
	Debug.Log("Server Initialized");
	spawnPlayer();
}// END OnServerInitialized

function OnConnectedToServer() {
	spawnPlayer();
}

...

2. DRAG ANG DROP the Cube from Hierarchy to Project, it will become a Prefab

3. Hierarchy> select Cube and press CANC on the keyboard

4. MAIN TOP MENU> GameObject> Create Empty, name it SpawnPoint, position it in the point where the Cube will appear.

5a. DRAG AND DROP Hierarchy> SpawnPoint over NetworkController> NetworkManagerScript> var spawnObject
5b. DRAG AND DROP Project> Cube over NetworkController> NetworkManagerScript> var playerPrefab

6. Add to NetworkManagerScript.js the code:


...

 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	} else {
	enabled = false;
	}
}// END Update()

...

For italian people: come funziona?
1. Trasformo il Cubo che rappresenta il nostro player in un Prefab e poi lo cancello dalla scena rimuovendolo da Hierarchy
2. Aggiungo un oggetto vuoto per segnare la posizione di generazione del Cubo
3. Con la modifica effettuata al codice ogni client genera il proprio Cubo, mi devo ricordare di assegnare in Inspector il Prefab che rappresenta il player e l’oggetto Empty che rappresenta la posizione in cui il player sarà generato.
5. In comune resta solo l’ambientazione costituita dal piano e dalla luce
6a. spawnPlayer() viene richiamata all’inizializzazione del server – OnServerInitialized() – per l’eseguibile server
6b. spawnPlayer() viene richiamata all’inizializzazione del client – OnConnectedToServer() – per l’eseguibile client
7. Se l’oggetto non è mio, disabilitalo – enabled = false; –

Unity 3D – RPC

0. Project> select the Cube> Add Component> Physic> Rigid Body> check ‘Is Kinematic’
NOTE: Without Rigid Body Component collisions will not be detected!

1. MAIN TOP MENU> GameObject> 3D Object> Sphere> Inspector> Collider> check ‘Is Trigger’, move it at Position X=-3 Y=0 Z=0

2. Attach to the Sphere, SphereScript.js


#pragma strict

function Start () {
}

function Update () {
}

function OnTriggerEnter (other : Collider) {
		Debug.Log("Collision detected!");
		renderer.material.color = Color(1,0,0,1);
}// END OnTriggerEnter

3. Play, ‘Start the Server’, move the Cube to collide with the Sphere, the Sphere will change color to red.

4. Hierarchy> select the Sphere> Inspector> ‘Add Component’> Miscellaneus> Network View:
– State Syncronization: Off, it is ideal for RPC
– Observed: None

Change SphereScript.js as:


function OnTriggerEnter () {
	Debug.Log("Collision detected!");	
	var newCol:Vector3 = Vector3(1,0,0);
	// Is sends the function SetColor(), to everyone and adds to the buffer
	networkView.RPC("SetColor",RPCMode.AllBuffered, newCol);
}// END OnTriggerEnter

// RPC Tag
@RPC
function SetColor(newColor:Vector3) {
	renderer.material.color = Color(newColor.x,newColor.y,newColor.z,1);
}// END SetColor()

For italian peolple: come funziona?
1. Non abbiamo bisogno di controllare costantemente il colore della sfera con una comunicazione di tipo Inspector> NetworkView> StateSyncronization, che viene disabilitata.
2. Operiamo il cambio di colore solo se c’è la collisione, quindi selezioniamo un metodo RPC
3. – networkView.RPC(“SetColor”,RPCMode.AllBuffered, newCol); – segnala a tutti i client connessi di avviare la funzione – SetColor() – che cambia il colore ad ogni sfera in ogni client connesso.
4. In definitiva posso avviare i 2 eseguibili, ogni giocatore muoverà il suo player (Cube) e il primo che arriva alla sfera gli farà cambiare colore in rosso.

Final Overview

Now a final overview:

Hierarchy:

– Main Camera
– Sphere (it is the goal to reach)
– Plane
– Directional Light
– NetworkController (Empty)
– SpawnPoint (Empty, give the PosXYZ to spawn Cube)

Project:

– Cube (prefab, It is our Player)
– Scene
– Scripts

Particular Components List:

– NetworkController (Empty)
— NetworkManagerScript.js to manage Server and Client

– Cube (prefab, It is our Player)
— Rigid Body – is kinematic
— Box Collider
— MovementScript,js to move the cube
— NetworkView – State Syncronization Reliable Delta Compressed

– Sphere (it is the goal to reach)
— Sphere Collider – is Trigger
— SphereScript.js to cahnge its color
— NetworkView – StateSyncronization None becuase it use RPC communication inside SphereScript.js

The final scripts:

Movement.js


#pragma strict
 
function Start () {
 
}// END Start()
 
function Update () {
 
 var horiz : float = Input.GetAxis("Horizontal"); // get AD buttons input
 var vert : float = Input.GetAxis("Vertical");    // get WS buttons input
 
 // Solo il server, cioè quello che parte per primo potrà spostare il cubo
 // Object instanted by me
 if (networkView.isMine){
 		transform.Translate(Vector3(horiz,0,vert));      // move along X -> AD and Z -> WS
	} else {
	enabled = false;
	}
}// END Update()

NetworkManagerScript.js


#pragma strict

var playerPrefab: GameObject;
var spawnObject: Transform;

var gameName: String = "MyFirstNetGame"; 

private var refreshing: boolean;
private var hostData: HostData[];

private var btnX:float; // Buttons Setup
private var btnY:float;
private var btnW:float;
private var btnH:float;

function Start () {
	btnX = Screen.width * 0.05; // Buttons Setup
	btnY = Screen.width * 0.05; // Dimension based on Screen.width
	btnW = Screen.width * 0.2;
	btnH = Screen.width * 0.2;

}

function startServer() {
    // This machine will be the Server
    // Initialize the server, number of allowed connection 32, listenport 25001, NOT have a public IP Adress
	Network.InitializeServer(32,25001, !Network.HavePublicAddress);
	
	// Register this server on the master server 
	// The Master Server is a meeting place that puts game instances in touch with the player clients who want to connect to them. 
	// Each individual running game instance provides a Game Type to the Master Server
	//(gameTypeName: string, gameName: string, comment: string = "")
	MasterServer.RegisterHost(gameName, "My Game Name", "This is a comment");
} // END startServer

function refreshHostList() {
    // check the number of hosts registered in MasterServer
    // controlla il numero di applicazioni registrate in MasterServer con 'gameName'
    // la registrazione al MasterServer può richiedere dai 3 ai 6 secondi
	MasterServer.RequestHostList(gameName);
	refreshing = true;
} // END refreshHostList

function spawnPlayer() {
	Network.Instantiate(playerPrefab, spawnObject.position, Quaternion.identity, 0);
}

// Called when Network.InitializeServer was invoked and has completed.
function OnServerInitialized() {
	Debug.Log("Server Initialized");
	spawnPlayer();
}// END OnServerInitialized

function OnConnectedToServer() {
	spawnPlayer();
}

// Called on clients or servers when reporting events from the MasterServer
function OnMasterServerEvent(mse:MasterServerEvent){
    // check if registration is ok
	if (mse == MasterServerEvent.RegistrationSucceeded){
	Debug.Log("Registrated Server!");
	}
}

// GUI Graphic User Interface
function OnGUI() {
//  if your peer type is NOT client AND is NOT server, cioè se non è già connesso
// questo if fa scomparire i bottoni una volta cliccato su 'Start Server'
if (!Network.isClient && !Network.isServer){
	if(GUI.Button(Rect(btnX, btnY,btnW,btnH),"Start Server")){
	Debug.Log("Starting Server");
	startServer();
	}
	
	if(GUI.Button(Rect(btnX, btnY*1.2+btnH,btnW,btnH),"Refresh Hosts")){
	Debug.Log("Refreshing");
	refreshHostList();
	}
	
	// se esistono dei gameName registrati su MasterServer
	if (hostData){
		// visualizza un array di bottoni con tutti i gameName registrati come MasterServer
		for(var i:int = 0; i<hostData.length; i++){
		    // se viene premuto il bottone
			if (GUI.Button(Rect(btnX*1.5 + btnW, btnY*1.2 + (btnH * i),btnW*3, btnH*0.5), hostData[i].gameName)){
				// Connect to the specified host (ip or domain name) and server port
				// Example: Network.Connect("127.0.0.1", 25000)
				Network.Connect(hostData[i]);
			}
		}
	}
}	
}// END OnGUI

function Update () {
    // se refreshing è true, cioè ho cliccato sul bottone 'Refresh Hosts'
	if (refreshing) {
		// se c'è almeno una registrazione
		if (MasterServer.PollHostList().Length > 0)  {
		// disabilita il refreshing per evitare che continui ad eseguirlo ad ogni ciclo Update
		refreshing = false;
		Debug.Log(MasterServer.PollHostList().Length);
		// array con tutte le registrazioni al MasterServer
		hostData = MasterServer.PollHostList();
		}	
	}// END Refreshing

}// END Update

SphereScript.js


function OnTriggerEnter () {
	Debug.Log("Collision detected!");	
	var newCol:Vector3 = Vector3(1,0,0);
	// Is sends the function SetColor(), to everyone and adds to the buffer
	networkView.RPC("SetColor",RPCMode.AllBuffered, newCol);
}// END OnTriggerEnter

// RPC Tag
@RPC
function SetColor(newColor:Vector3) {
	renderer.material.color = Color(newColor.x,newColor.y,newColor.z,1);
}// END SetColor()

That’s all folks!

NOTE: You will notice a small delay between the input and the actual movement, this is because the position is updated after the new data is received. All we can do is predict what is going to happen based on the old data.

One method to predict the next position is by taking the velocity into account. A more accurate end position can be calculated by adding the velocity multiplied by the delay.

See the lesson 2 about Multiplayer – Latency Compensating Methods at:
http://www.lucedigitale.com/blog/unity3d-tutorials-multiplayer-latency-compensating-methods/

My official website: http://www.lucedigitale.com

References:

– http://docs.unity3d.com/Manual/net-HighLevelOverview.html
– http://www.inetdaemon.com/tutorials/internet/ip/whatis_ip_network.shtml
– http://whatismyipaddress.com/nat
– http://vimeo.com/33996023#
– http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/

Extra resources:

– http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking
– http://developer.valvesoftware.com/wiki/Lag_Compensation
– http://developer.valvesoftware.com/wiki/Working_With_Prediction
– http://www.gamasutra.com/resource_guide/20020916/lambright_01.htm

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Tutorials – Multiplayer Introduction