HTML and CSS Reference
In-Depth Information
When the slave receives the ball message indicating an updated ball position, callback updates the position
and direction of the ball and then manually calls the step method to advance the ball by whatever the length
of the network delay is between the two clients.
With the sprites defined, there is the additional complexity of setting up the scene according to whether the
player is the master of the slave. It does this by looking at the gameType global variable to put the player on
top and the enemy on the bottom if this client is the master or vice versa if it's the slave. Then it just inserts a
ball and lets it fly.
The last chunks of code are the socket events. The slave and master events, if you remember how the
server was set up, kick off the game by indicating the player is either the master or the slave and then stage
the game scene. The end event, called when the other player disconnects, simply stops the game by clearing
the stage.
More complicated is the delay event. This event is sent every two seconds via the final setInterval
call at the end of the code, which sends a message with a steps variable and the current time in milliseconds.
As you saw in the server code, this message is bounced from one client back to the originating client as a way
to measure the delay in sending packets end to end. The client looks at the step variable and if it's equal to 3, it
knows the message has made a complete trip.
When the originating server receives the message back, it grabs the updated time in milliseconds and calcu-
lates the round-trip delay by subtracting the current time from the time it sent the message originally. Dividing
that number in half gets the time it takes to send a message from one client to another via the server.
Pulling it all together, you now have a game where two players can play directly against each other using a
simple form of client-side prediction to try to keep the players in sync with each other.
This chapter examined how to use WebSockets and a library called to build real-time games where
multiple players can interact directly with each other. It showed how to take code that is similar to a single-play-
er game from earlier in the topic and change it into a multiplayer game that passes messages through a central
server. Using the code presented here you should be able to build both real-time and semi-real-time games that
have near-instant interaction between multiple players.
Search WWH ::

Custom Search