Making a Multiplayer Game
Whether you're developing a new game or transitioning an existing one to a multiplayer format, Playroom simplifies the process with low-code integration. Here's a general outline of the steps involved:
Steps
Add Playroom
Add Playroom to your game. See Setup for ways to do this.
Insert Coin!
Tell Playroom to start! Playroom Kit will automatically handle room creation, joining and also let players pick their names, colors and avatars. Once host taps "Launch", your game will start.
// Show Playroom lobby UI, Playroom will handle players joining etc and wait for host to tap "Launch"
await insertCoin();
// Players are in this room! (your game code below)
startGame();
Set game state you want to sync
Playroom will sync state across all players. This can be anything like time left, physics objects, etc. Ideally only the host should set the game state. Other players should then receive the game state from the host and update their game accordingly.
// On one player
setState("timeLeft", 60);
// On other players
const timeLeft = getState("timeLeft");
Handle players joining and quiting
When a player joins, you probably need to add a player sprite to the game. When a player quits, you need to remove the player sprite from the game.
In Playroom Kit, you can use the onPlayerJoin
and onQuit
callbacks to handle this:
onPlayerJoin(playerState => {
// PlayerState is this player's multiplayer state along with it's profile.
// Probably add a player sprite to the game here.
playerState.onQuit(() => {
// Handle player quitting. Maybe remove player sprite?
});
});
Pass player input to Playroom
Input can be anything like joystick data, button presses etc. Save current input to current player's state. Host will read input state and update the game state. No network code needed!
joystick.on("move", (e, data) => {
// Set current player's input state to Playroom.
myPlayer().setState("input", data.direction);
});
Pass your game state to Playroom
Things like player position, health, score etc. Ideally only the host should set the game state. Other players will only receive the game state from the host and update their game accordingly.
// Host only
updatePlayer(player) {
const input = player.state.getState("input")
// ...
// Update player position based on player input
// ...
player.state.setState("position", {
x: newX,
y: newY,
});
}
Demo #1
Below is a live preview of a simple flying plane game adapted from this code by Codrops (opens in a new tab).