Skip to content

Multiplayer ​

A shared world runs in a room on a Colyseus server. Turn multiplayer on in the editor's Environment panel; it adds a server/ folder to the project and runs that server for you while you test.

Making a game multiplayer ​

  1. Turn it on: Environment panel, Multiplayer, Enabled. Nothing changes for a single player until something is shared.
  2. Give each player a character: make the player a prefab, add an empty object where players start, then Add Component → Multiplayer → Player Spawner and name the prefab.
  3. Share what everyone should see move: select it, then Add Component → Multiplayer → Share With Players.
  4. Test it: Play with 2 players opens a window per player against a server on your own machine.
  5. Decide where it runs when published: Relu's servers need no setup, but only run the standard room. Your own server runs your server/rooms/game.ts, which is where rules that mustn't be cheated belong.

The agent can do all of this: ask it to make the game multiplayer.

Who moves what ​

Everything shared has one owner, the client that simulates it. The owner moves it at once and sends updates; everyone else plays them back a moment in the past, which is what makes it smooth.

  • A scene object with a Network Identity is owned by the host: the first player in the room, then the longest connected. When the host leaves, the next player takes over.
  • A spawned object is owned by whoever spawned it, and leaves with them.

Components ​

ComponentWhat it does
Network IdentityMarks an entity as shared.
Network TransformShares its position and rotation. interpolationMs trades smoothness for how current it looks.
Networked PropsNamed values shared with everyone, such as health. Only the owner can change them.
Network SpawnerGives each player a prefab of their own, placed around this entity.

From a script ​

this.network is null in a single-player run, so a script can work both ways. A script on a shared entity should only drive it when it's the owner:

ts
import { Behaviour, KeyboardKeys } from "@relu-interactives/spatial-ecs";

export class Player extends Behaviour {
  protected onUpdate() {
    if (this.network && !this.network.isOwner) return; // someone else moves this one
    if (this.world.getKey(KeyboardKeys.W)) {
      this.transform.position.z -= 3 * this.deltaTime;
    }
  }
}

Shared values, and hearing them change:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class Health extends Behaviour {
  takeHit(damage: number) {
    const hp = Number(this.network?.getProp("hp") ?? 100);
    this.network?.setProp("hp", hp - damage);
  }

  onNetworkProp(key: string, value: unknown) {
    if (key === "hp") console.log("health is now", value);
  }
}

Messages go to everyone else in the room. Spawn something everyone sees with spawn:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class Gun extends Behaviour {
  protected init() {
    this.network?.onMessage("shot", (payload, from) => {
      console.log(from, "fired", payload);
    });
  }

  fire() {
    this.network?.send("shot", { power: 3 });
    this.network?.spawn("assets/bullet.prefab", {
      position: this.transform.position,
    });
  }

  onPlayerJoin(playerId: string) {
    console.log(playerId, "joined; there are", this.network?.players.length);
  }
}

Sounds everyone hears ​

this.network.playSlot plays a sound-bank slot here and for everyone else in the room. Each client needs the bank loaded. If a slot's chance or cooldown keeps it quiet, no one hears it.

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class Shooter extends Behaviour {
  async init() {
    await this.loadSoundBank("assets/audio/weapons.soundbank.json");
  }

  fire() {
    const { x, y, z } = this.transform.position;
    this.network?.playSlot("shot", { position: { x, y, z } });
  }
}

Only slot ids travel, so a client can't make another one load a file. The room limits each player to 30 sounds a second.

Voice chat ​

Turn on voice in the project's Multiplayer settings and players get a mic button. Voice is direct between players: the game server only passes the messages that set each connection up, and never hears the audio. Nothing is captured until a player turns voice on, and only others who turned it on can hear them.

Voices play through the voice bus, so setBusVolume("voice", …) applies and music ducks while someone talks. Each voice comes from that player's character, the first thing they spawned. To hear everyone everywhere, set positional to false.

To build your own controls, use this.network.voice. It's null when the project doesn't have voice on:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class VoiceKey extends Behaviour {
  // call from a key or a tap: that's what lets the browser ask for the mic
  async toggle() {
    const voice = this.network?.voice;
    if (!voice?.available) return;
    if (voice.state === "off") await voice.enable();
    else voice.disable();
  }

  whoIsTalking() {
    return this.network?.voice?.peers.filter((peer) => peer.talking) ?? [];
  }

  quiet(playerId: string) {
    this.network?.voice?.setPeerMuted(playerId, true);
  }
}

Things to know:

  • Rooms stop at 8 people in voice. Everyone sends to everyone, so each person's upload grows with the room. The quality steps down as it fills and on a poor connection. A ninth person sees "Voice is full in this room".
  • A mic needs https. voice.available is false on a plain http page, except localhost.
  • Direct connections show players each other's IP address. On a public game, set VOICE_RELAY_ONLY=1 on the server to send everything through the relay instead. That needs a TURN relay, and all voice then costs relay bandwidth. Without a relay, voice stays off rather than connecting directly.
  • Some networks can't connect directly. Mobile carriers often block it. Set TURN_URLS and TURN_SECRET on your server to give those players a relay, using a TURN server such as coturn in its use-auth-secret mode. Without one, those players connect to voice but hear nothing.

VR and mixed reality ​

Multiplayer works the same way in an XR project, with a few things added.

  • Players see each other. Each player's head and hands are shared and drawn for everyone else: a head and two hands in VR, and in mixed reality, where you see the real person, a ring at their head and dots on their fingertips. There's nothing to set up. To change how players look, add XR Multiplayer to the XR Rig (Add Component → Multiplayer).
  • Grabbing hands objects over. Give a shared object an XR Interactable and pick it up: it becomes yours while you hold it and after you let go, until someone else picks it up. While one player holds it, another can't take it out of their hand. A dynamic body someone else owns follows their updates on your screen instead of falling on its own.
  • Voice comes from each player's head.
  • A player spawner places players, in VR: with no prefab, each player starts somewhere around it, facing the middle. In mixed reality you stand where you are.
  • Players in one room can line up. Turn on colocation and each player touches the same two real points, so a board on a real table is in the same place for both. See Colocation.
XR Multiplayer fieldWhat it does
avatarStyleauto (full in VR, subtle in passthrough), full, subtle or none.
headPrefab, leftHandPrefab, rightHandPrefabDraw these instead of the default head and hands. They're spawned for each player on each screen and moved every frame.
sendRateUpdates a second. 20 by default, 30 at most.
interpolationMsHow far in the past others are drawn. More is smoother.
shareHandJointsSend tracked fingers, not just the wrist.
nameTagsA name over each head. Set one with this.network.setName(); otherwise it's "Player 2" and so on.
colocation, calibrateOnStart, minPointDistanceSee Colocation.

A head and both tracked hands come to about 350 bytes, so a player sends about 7 KB a second at 20 updates a second, and 450 bytes a second with no hands. Hand joints travel as positions to a tenth of a millimetre.

A script can take an object itself, for a move that isn't a grab, such as tapping a piece to move it:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class Piece extends Behaviour {
  moveTo(x: number, z: number) {
    const network = this.network;
    if (network && !network.isOwner && !network.take()) return; // someone else has it
    this.transform.position.x = x;
    this.transform.position.z = z;
    network?.drop();
  }
}

take() only works on objects in the scene, not spawned ones, and the room says no while someone else holds it. this.network.holder says who does.

Outside a headset, a desktop window sends its camera as the head, so Play with 2 players shows each window's view to the other. Drag to look and use WASD to move.

Pausing ​

A room has no shared pause. world.pause() pauses this player only, and the first time it happens in a room the console says so. The connection stays up, voice chat carries on, other players keep moving, and their sounds still play. Your own character stops, so to them you stand still.

To stop everyone, send a message and have every client pause when it arrives, or show a menu without pausing the world. See Pausing the Game.

Where a published game runs ​

Set this in the project's Multiplayer settings. Local tests always stay on your machine.

  • Relu's servers. Nothing to set up. Your plan sets how many players can be online at once in the game, across all its rooms, and whether voice chat is on. Past the limit, a new player sees that the game is full and plays alone. These servers run the standard room only, so server/rooms/game.ts doesn't run there.
  • Your own server. The editor gives you one command to run on a machine you own. This is the choice for server rules, and it isn't limited by your plan.

Server rules ​

Clients can't be trusted, so anything that decides who won belongs on the server, in server/rooms/game.ts. Every hook is optional, and with none the room just relays:

ts
const game: RoomHooks = {
  maxClients: 8,
  // false moves the player back
  onPose: (room, client, entity, next) => next.y > -50,
  // false keeps a message from the other players
  onMessage: (room, client, name, payload) => name !== "cheat",
  // false keeps a player from taking an object (a grab)
  onTake: (room, client, entity) => entity.id !== "scene-12",
};

Head and hand updates and colocation points are checked for size and shape, limited per player, and passed on; they're never stored on the server.