<commit_before>---
title: Real Time Multiplayer
template: tutorial-page.tmpl.html
---

<iframe src="http://playcanv.as/p/0lGQe06X" ></iframe>
*Use WASD to move the player around. If you only see one capsule, try opening this page in another tab or on another computer.*

In this tutorial we’ll cover how to setup basic multiplayer project, using Node.js and Socket.io. It will also cover the basics of sending and receiving messages to/from the server. By the end of the demo you should have a project similar to the one above.

## Setting up the Server

Before you can work on anything multiplayer related, you’ll need a server to process your game’s data. For this tutorial we’ll be using our own computer, but in the future you may want to look into server hosts such as [Amazon][5] or [OpenShift.][6]

Head over to nodejs.org and download and install the recommended version of Node.js.

Open up a command prompt window (terminal for Mac) and type in:

~~~
npm install socket.io
~~~

It should take a few seconds. When it's done, you should have Node.js and Socket.io installed on your computer.

![Socket Installed][1]

Next, we’ll need to create a server file. Open up a text editor and type in the following:
	
~~~javascript~~~
var server = require('http').createServer();
var io = require(‘socket.io')(server);

io.sockets.on('connection', function(socket) {
});

console.log ('Server started.');
server.listen(3000);
~~~

Notice that the server is listening on port 3000. We’ll come back to this. Save it in your home folder as ‘server.js’. Make sure it’s saved as a Javascript file and not Server.js.txt. To start your server, open up a command prompt window and type in:

~~~
node server.js
~~~

You should see ‘Server started.’ Congratulations, you’re now running your very own server.

![Server Started][2]

## Setting up the Project

Open up PlayCanvas and create a new project. First, you’ll want to create a new script called ‘socket.js’. Next, add it to your projects priority list.

![Script Priority][3]

Open the script and replace the contents of the file with [this.][4]

Now we need to create a new script to handle the network logic. Create a new script called ‘Network.js’. We first need to create a connection to the server. We can do this by adding this line in the initialize method:

~~~javascript~~~
this.socket = io.connect(‘http://localhost:3000/');
~~~

‘http://localhost' is the address of your server and the ‘3000’ is the port. Since we’re connecting to our own computer, we use localhost. If you were hosting elsewhere this is what you'd want to change. Make sure the port you’re using to connect is the same as the one you set in the server file. The project is now setup to send and receive messages to/from the server.

## Server and Client Communication

The way you can send data between the client and server is with the socket connection we made earlier. To send data from the client, we use the emit function. Here’s an example:

~~~javascript~~~
this.socket.emit (‘playerJoined’, ‘John’);
~~~

This emits a message called ‘playerJoined’, with the data ‘John’. For the server to receive the message, we need to write in the server file:
	
~~~javascript~~~
socket.on (‘playerJoined’, function (name) {
	console.log (name);
});
~~~

This will log whatever data is sent to the server when ‘playerJoined’ is emitted.

For this demo, we’re aiming to have players move around with others in real time, so we'll need to create an environment. Start by create an entity to use as a ground, and add a collision box and static rigidbody.

![Ground Entity][7]

Next we’ll need a player to control. Create a new capsule and call it ‘Player’. add a dynamic rigidbody and collision box, and change the rigid body settings to match the picture below.

![Player Entity][8]

Duplicate the player entity and rename it as 'Other'. This is the entity we'll be using to simulate other players in the game.

Add a script component to your player, and attach a new script called 'Movement.js':

~~~javascript~~~
pc.script.attribute('playerSpeed', 'number', 30, {displayName: 'Player Speed'});

pc.script.create('Movement', function (app) {
	// Creates a new Movement instance
	var Movement = function (entity) {
		this.entity = entity;
		this.force = new pc.Vec3 ();
	};

	Movement.prototype = {
		// Called every frame, dt is time in seconds since last update
		update: function (dt) {
			var forward = this.entity.forward;
			var right = this.entity.right;
            
			x = 0;
			z = 0;
            
			if (app.keyboard.isPressed(pc.KEY_A)) {
				x -= right.x;
				z -= right.z;
			}		

			if (app.keyboard.isPressed(pc.KEY_D)) {
				x += right.x;
				z += right.z;
			}

			if (app.keyboard.isPressed(pc.KEY_W)) {
				x += forward.x;
				z += forward.z;
			}

			if (app.keyboard.isPressed(pc.KEY_S)) {
				x -= forward.x;
				z -= forward.z;
			}
                
			if (x !== 0 || z !== 0) {
				x *= dt;
				z *= dt;
                <commit_msg>Update real-time-multiplayer.md<commit_after>---
title: Real Time Multiplayer
template: tutorial-page.tmpl.html
---

<iframe src="http://playcanv.as/p/0lGQe06X" ></iframe>
*Use WASD to move the player around. If you only see one capsule, try opening this page in another tab or on another computer.*

In this tutorial we’ll cover how to setup basic multiplayer project, using Node.js and Socket.io. It will also cover the basics of sending and receiving messages to/from the server. By the end of the demo you should have a project similar to the one above.

## Setting up the Server

Before you can work on anything multiplayer related, you’ll need a server to process your game’s data. For this tutorial we’ll be using our own computer, but in the future you may want to look into server hosts such as [Amazon][5] or [OpenShift.][6]

Head over to nodejs.org and download and install the recommended version of Node.js.

Open up a command prompt window (terminal for Mac) and type in:

~~~
npm install socket.io
~~~

It should take a few seconds. When it's done, you should have Node.js and Socket.io installed on your computer.

![Socket Installed][1]

Next, we’ll need to create a server file. Open up a text editor and type in the following:
	
~~~javascript~~~
var server = require('http').createServer();
var io = require(‘socket.io')(server);

io.sockets.on('connection', function(socket) {
});

console.log ('Server started.');
server.listen(3000);
~~~

Notice that the server is listening on port 3000. We’ll come back to this. Save it in your home folder as ‘server.js’. Make sure it’s saved as a Javascript file and not Server.js.txt. To start your server, open up a command prompt window and type in:

~~~
node server.js
~~~

You should see ‘Server started.’ Congratulations, you’re now running your very own server.

![Server Started][2]

## Setting up the Project

Open up PlayCanvas and create a new project. First, you’ll want to create a new script called ‘socket.js’. Next, add it to your projects priority list.

![Script Priority][3]

Open the script and replace the contents of the file with [this.][4]

Now we need to create a new script to handle the network logic. Create a new script called ‘Network.js’. We first need to create a connection to the server. We can do this by adding this line in the initialize method:

~~~javascript~~~
this.socket = io.connect(‘http://localhost:3000/');
~~~

‘http://localhost' is the address of your server and the ‘3000’ is the port. Since we’re connecting to our own computer, we use localhost. If you were hosting elsewhere this is what you'd want to change. Make sure the port you’re using to connect is the same as the one you set in the server file. The project is now setup to send and receive messages to/from the server.

## Server and Client Communication

The way you can send data between the client and server is with the socket connection we made earlier. To send data from the client, we use the emit function. Here’s an example:

~~~javascript~~~
this.socket.emit (‘playerJoined’, ‘John’);
~~~

This emits a message called ‘playerJoined’, with the data ‘John’. For the server to receive the message, we need to write in the server file:
	
~~~javascript~~~
socket.on (‘playerJoined’, function (name) {
	console.log (name);
});
~~~

This will log whatever data is sent to the server when ‘playerJoined’ is emitted.

For this demo, we’re aiming to have players move around with others in real time, so we'll need to create an environment. Start by create an entity to use as a ground, and add a collision box and static rigidbody.

![Ground Entity][7]

Next we’ll need a player to control. Create a new capsule and call it ‘Player’. add a dynamic rigidbody and collision box, and change the rigid body settings to match the picture below.

![Player Entity][8]

Duplicate the player entity and rename it as 'Other'. This is the entity we'll be using to simulate other players in the game.

Add a script component to your player, and attach a new script called 'Movement.js':

~~~javascript~~~
pc.script.attribute('playerSpeed', 'number', 30, {displayName: 'Player Speed'});

pc.script.create('Movement', function (app) {
	// Creates a new Movement instance
	var Movement = function (entity) {
		this.entity = entity;
		this.force = new pc.Vec3 ();
	};

	Movement.prototype = {
		// Called every frame, dt is time in seconds since last update
		update: function (dt) {
			var forward = this.entity.forward;
			var right = this.entity.right;
            
			var x = 0;
			var z = 0;
            
			if (app.keyboard.isPressed(pc.KEY_A)) {
				x -= right.x;
				z -= right.z;
			}		

			if (app.keyboard.isPressed(pc.KEY_D)) {
				x += right.x;
				z += right.z;
			}

			if (app.keyboard.isPressed(pc.KEY_W)) {
				x += forward.x;
				z += forward.z;
			}

			if (app.keyboard.isPressed(pc.KEY_S)) {
				x -= forward.x;
				z -= forward.z;
			}
                
			if (x !== 0 || z !== 0) {
				x *= dt;
				z *= dt;
                
{'fraction_non_alphanumeric': 0.09751453197033473, 'fraction_numerical': 0.006814992984566046, 'mean_word_length': 3.5587026039287344, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3014746', 'n_tokens_mistral': 3084, 'n_tokens_neox': 2820, 'n_words': 1419}