Multiplayer Network Games - Setting Sprite Speed Synchronously
-
Introduction
In most multiplayer network games, each player would control a sprite to navigate the game world. For example, in a pong game, each player would move their own bouncing board up and down.
Although we can set the position of a sprite synchronously for all players, a much more common way of moving sprites in a network game is to set its x and y speeds. This will ensure the sprite moves smoothly through a continuous path, which is critical for handling collisions between sprites.
Setting X and Y Speeds Synchronously
To set a sprite’s speed synchronously, we can use the following block:
This block takes 2 inputs, which are the speed in x and y directions. The x speed controls how many steps the sprite would move per second horizontally, and if it is negative, that means the sprite is moving to the left. Similarly, the Y speed controls how fast the sprite moves vertically, and negative Y speed means the sprite will be moving downwards.Note that the sprite will stop at the world boundary or when it collides with another sprite.
Setting Direction and Speed Synchronously
Sometimes it is simpler to think of a sprite as moving in a given direction at a certain speed. Therefore, another block is available to set the sprite’s speed this way:
The first input is the speed at which the sprite will be moving along the given direction. When it is negative, then the sprite is moving backwards along that direction.The second input is the moving direction in degrees. It follows the same convention as the “direction” property of sprites. For example, when it is 0, the direction points up (along the Y axis). When it is 90, it points to the right (along the X axis).
Similar to the previous block, this sprite and all its replicates on other hosts will be updated to this new speed and direction at the same time.
Demo
In this demo project, we repeatedly set the ball’s speed randomly, and its copy on the second computer will move with the same speeds in sync.
To run it:
- Create a new game as host using the “BlueBall” sprite:
- Join the game from another account (in an incognito browser tab) using the “YellowBall” sprite:
- In the “BlueBall” sprite, repeatedly set the ball’s speeds to random values synchronously:
-
In the “YellowBall” sprite, run the same blocks
-
As a result, both balls will be moving to random positions, and the 2 tabs will be in sync all the time:
Note that there might be some delay before the copy sprite changes its moving speed. That’s because the speed update message needs to travel to the game server first, and then it is sent to the guest player’s computer.Here is the project URL: https://play.cr eaticode.com/projects/6606029025dc753d5b67bc62