🕹️ | Making Multiplayer

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

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 UI, let it handle players joining etc and wait for host to tap "Launch"
await insertCoin();
 
// Start the game! (your game code below)
startGame(); 

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. Host will receive input events 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 send 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).