Building a Multiplayer Pong Game Using Socket.io

Using a WebSocket-based technology opens up a lot of different possibilities for multiplayer game play, including real-time action games. To see this in action, you build a two-player pong game where players bat a ball back and forth across the screen.

In the game, both players simulate the entire game on each device; however, one player acts as the “master,” and one acts as the “slave.” The master controls the true location of the ball and sends updates periodically to the slave, who updates the location of the ball to reflect the true game state.

Dealing with Latency

One of the problems with multiplayer, real-time gaming is the issue of latency. Depending on the speed of the network and the distance between the server and players, latencies of more than 100ms and dropped packets are common on mobile. This means that to keep the action going you need to do some predictive modeling that takes latency into account.

Your pong game deals with this by calculating a “delay,” which is the time it takes to get a packet from one player to another. It uses that delay to calculate how much farther the ball or other player should have moved from the time the data left one player to the time it arrived at another.

Because both games simulate the path of the ball, each player should see the ball updating smoothly while the slave player occasionally sees a blip course correction if the ball on one device is out of sync with the other device.

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.