Create A Basic Multiplayer Game In Phaser 3 With Socket.io – Part 1

In this multipart tutorial, we will be using Phaser 3 and Socket.io to create a simple multiplayer game. For our multiplayer game, we will follow the client-server game architecture. If you are not familiar with the client-server game architecture, the client is responsible for displaying the game to the player, handling the player’s input, and for communicating with the server. The server on the other hand, is responsible for broadcasting that data to each client.

The goal of this tutorial is teach you the basics of creating a multiplayer game. You will learn how to:

  • Setup a Node.js and Express server that will render our game and communicate with it.
  • Setup a basic Phaser 3 game that will act as our client.
  • Use Socket.io to allow the server and the client to communicate.

You can download all of the files associated with the source code for part one here.

Learn Phaser 3 with our newest Mini-Degree

The HTML5 Game Development Mini-Degree is now available for Pre-Order on Zenva Academy. Learn to code and make impressive games with JavaScript and Phaser 3!

Get Instant Early Access

Tutorial Requirements

For this tutorial, we will be using Node.js and Express to create our server. We will also be using NPM to install the required packages we need for the server to run. In order to follow along with this tutorial, you will need to have Node.js and NPM installed locally, or you will need access to an environment that already has them installed. We will also be using the Command Prompt (Windows) / Terminal (Mac) to install the required packages, and to start/stop our Node server.

Having a prior experience with these tools is a plus, but it is not required for this tutorial. We will not be covering how to install these tools as the focus of this tutorial is making a game with Phaser. The last thing you will need is an IDE or Text Editor for editing your code.

To install Node.js, click the link here: and choose the LTS version. You can download and use the current version with this tutorial, however the LTS version is recommended for most users. When you install Node.js, NPM will also be installed on your computer. Once you have these tools installed, you can move on to the next part.

Setting up the server

The first thing we are going to do is create a basic Node.js server that will serve our game files. To get started, create a new folder on your computer, it can be called anything you want. Then navigate inside this folder and create a new file called  server.js. Open up  server.js and add the following code to it:

In the code above we:

  • referenced the express module, which is a web framework that will help us render our static files.
  • created a new instance of express and called it  app.
  • supplied the app to the HTTP server, which will allow express to handle the HTTP requests.
  • updated the server to render our static files using  express.static built-in middleware function in Express.
  • told the server to serve the  index.html file as the root page.
  • had the server start listening on port 8081.

Before we can run the server, we will need to install the required modules for the server. Open your terminal / command prompt, and navigate to your project folder. Once there you will need to run the following command:  npm init -f. This will create a  package.json file in your project folder. We will use this file to keep track of all the packages that our project depends on.

Now, we will install  express. In your terminal run the following command:  npm install --save express. This will create a folder called node_modules in your project folder, and by adding the  --save flag to the command, npm will save this package in our  package.json file.

Setting up the client

With the basic server code finished, we will now work on setting up our client side code. In your project folder, create a new folder called  public. Any file we put in this folder will be rendered by the server that we setup. So we will want to put all of our static client side files in this folder. Now inside the public folder, create a new file called  index.html. Open up  index.html and add the following code to it:

In the code above, we setup a simple HTML page and we referenced two JavaScript files,  phaser.min.js (the phaser game framework) and  game.js (our Phaser game code). Back in the  public folder, create a new folder called  js , and in this folder create a new file called  game.js. Open up  game.js and add the following code to it:

Let’s review the code we just added:

  • We created the configuration that will be used for our Phaser game.
  • In the config object, in the type field, we set the renderer type for our game. The two main types are Canvas and WebGL. WebGL is a faster renderer and has better performance, but not all browsers support it. By choosing AUTO for the type, Phaser will use WebGL if it is available, otherwise it will use Canvas.
  • In the config object, the parent field is used to tell Phaser to render our game in an existing  <canvas>  element with that id if it exists. If it does not exists, then Phaser will create a  <canvas>  element for us.
  • In the config object, we specify the width and height of the viewable area of our game.
  • In the config object, we enabled the arcade physics that is available in Phaser, and we set the gravity to 0.
  • In the config object, we embedded a scene object which will use the  preload, update, and  create functions we defined.
  • Lastly, we passed our config object to Phaser when we created the new game instance.

With our basic client side code setup, we will now test our server and make sure everything is working correctly. Back in the terminal / command prompt, run the following command:  node server.js and you should see the following line appear  Listening on 8081. Now, if you open up your web browser and navigate to:  http://localhost:8081/ , you should see black box on the web page, and if you open the console in the developer tools, you should see a log with the version of Phaser your game is running.

Adding Socket.IO

With our server now rendering our game, we will now work on adding Socket.IO to our game. If you are not familiar with Socket.IO, it is a JavaScript library that enables real-time, bi-directional communication between web clients and servers. To use Socket.IO, we need to update our client and server code to enable the communication between the two.

Back in your terminal, run the following command:  npm install --save socket.io. If your server is still running, you can either: open a new terminal window and run the code in your project folder, or stop the server (CTRL + C) and then run the command. This will install the Socket.IO node package and save it in our  package.json file.

Now, in  server.js add the following code below the  var server = require('http').Server(app); line:

Then add the following code above the  server.listen line:

In the code above we:

  • referenced the socket.io module and had it listen to our server object.
  • added logic to listen for connections and disconnections.

Next, we will update the client side code to include the Socket.IO library. Open up  index.html and add the following line at the top of the  <body> element:

Then, open up  game.js and add the following line inside the create function:

Now, if you start the server back up again, and refresh your game in your browser, you should see the user connected / disconnected messages in your terminal.

Adding players – Server

Now that we have our socket connections setup, we can move on to adding players to our game. In order to keep all of the players games in sync, we will need to notify all players when an user connects or disconnects from the game. Also, when a new player connects we will need a way to let the player know of all the other players in the game. To do all of this we will need to store some player data, and we will use the socket connections to send messages to our players.

For this tutorial, we will store the player data in memory on the server. Normally, we would want to store this data in some type of database, that way it would be persistent, and if the server fails, we could easily recover the state of the game.

In  server.js add the following line below the  io variable:

We will use this object to keep track of all the players that are currently in the game. Next, in the callback function of the socket.io  connection event add the following code below the  console.log('a user connected'); line:

Let’s review the code we just added:

  • When a player connects to the web socket, we store some player data in the  players object and we use the  socket.id as the key.
  • We are storing the rotation, x, and y position of the player, and we will use this to control were we create sprites on the client side, and use this data to update all players games. We also store the playerId so we can reference it in the game, and we added a team attribute that will be used later.
  • We used  socket.emit and  socket.broadcast.emit to emit an event to the client side socket.  socket.emit will only emit the event to this particular socket (the new player that just connected).   socket.broadcast.emit will send the event to all other sockets (the existing players).
  • In the  currentPlayers event, we are passing the  players object to the new player. This data will be used to populate all of the player sprites in the new player’s game.
  • In the  newPlayer event, we are the passing the new player’s data to all other players, that way the new sprite can be added to thier game.

When a player disconnects, we need to remove that player’s data from our  players object, and we need to emit a message to all other players about this user leaving, that way we can remove that player’s sprite from the game.

In the callback function of the socket.io  disconnect event add the following code below the  console.log('user disconnected'); line:

Your  server.js file should look like the following:

Conclusion

With our server code for adding players in place, this brings part one of this tutorial to an end. In part two we wrap up our multiplayer game by:

  • Adding the client side logic for adding players to our game.
  • Adding logic for player input.
  • Adding collectibles for the players to collect.

I hoped you enjoyed part one of this tutorial and found it helpful. If you have any questions, or suggestions on what we should cover next, let us know in the comments below.

Published by

Scott Westover

Scott Westover is a Fullstack Developer who loves coding, writing tutorials, participating in game jams, and learning about new technologies. When he is not coding, he is either spending time with his wife and two kids or is reading a great book. Scott is looking to form connections and share his knowledge. Connect with Scott on Linkedin.

Share this article

7
Leave a Reply

avatar
7 Comment threads
0 Thread replies
5 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
EnrymionLugude JutustajaLee Ramersammaddy Recent comment authors
newest oldest most voted
maddy
Guest
maddy

Thanks for posting this:)

sam
Guest
sam

Hi, thanks for the tutorial. I have a question, why are there spawning 30 ships when i open the game in two diffrend browsers and wait a few minutes? there should still be two ships not 30 right?

Lee Ramer
Guest
Lee Ramer

Hi Scott, great tutorial, just started learning JS and Phaser in the last few months. Question about multiplayer and scenes. If I create a socket in the first scene, how do I transfer that socket and use socket.on for data transfer to other scenes. I am trying to make a program that allows 2 players to play against each other in various games that start from one beginning Main scene. and would finish back at the Main scene with the total games one for each player. I can’t yet figure out how to use the same socket.io for each player… Read more »

Lugude Jutustaja
Guest
Lugude Jutustaja

Mistake in section “Setting up the client”. Is written:

Should be:

Otherwise in part 2 of this tutorial, it will not draw the space ships. It is written correctly in the attached source files.

Lugude Jutustaja
Guest
Lugude Jutustaja

Mistake in section “Setting up the client”. Is written:
“”
Should be:
“”
Otherwise in part 2 of this tutorial, it will not draw the space ships. It is written correctly in the attached source files.

Lugude Jutustaja
Guest
Lugude Jutustaja

Mistake in section “Setting up the client”. Inside the script src part, it says “phaser@3.0.0”. It should be “phaser@3.3.0”. Otherwise in part 2 of this tutorial, it will not draw the space ships. It is written correctly in the attached source files.

Enrymion
Guest
Enrymion

At the end of adding Socket.io section it could be clearer that you do need to restart the server(if you opened a new terminal window when it was suggested as an option) also just to make it clear when it says add a line inside the create function it means between the {} in “function create() {}” line.