Last part of the tutorial, is handling states, the server needs to control client states, in a multiplayer game, both client and server simulate the movements, then the server will send states to each client updating the positions of the clients in the game. In the tutorial we synchronize a minimum set of information and trust the client side. This is how it is done:
- when a player issues a command (movement and fire), the local code will not handle it directly.
- It will be sent to the server, the serve will then loop through all clients and send the clients input
- each client will apply this input to the client side copy of the Tank
- the Tank handle the input sent by the server as it was issued by a local input
also each time an input information is sent, we will send the information about each tanks position, this information will be used to synchronize tank states with all connected clients. This is the code that will handle this.
Reminder: Methods using exports namespace can be called from the server.
The updateState method will update Tank.Cursor with the shared input but will also correct the Tank position and angle. Now to handle this into the Tanks update method, we need to edit the Tank.prototype.update and add this code.
in this piece of code we are first detecting if the local player had made an input like, mouse click of WASD, if they have we send the information of the input to the server through the eurecaServer handleKeys method this method will then send back the input to all connected clients.
Now we begin working on the Server side code.
First we need to allow the newly declared client method into the server (updateState)
Then we declare the handleKeys method, which was mentioned above. However i changed the method name to handleState, as it makes more sense to me.
And then a modification to the handshake method.
I actually can’t show you the change because in the earlier blogs i showed the finished version. But it was there.
If we start the server now and run the game, both players can be seen in different locations on each screen. If you move one in one screen it will move in the other.
Now that this tutorial was finished, i began working in my own code and modifications to the game.