GameCrew AIEarly access
Sign in
Three.jsgameplayCompile-verified pattern

Multiplayer Room State Sync & 60 Hz Avatars in Three.js

Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.

  • multiplayer
  • networking
  • rooms
  • interpolation
  • host-migration
  • net

When to Use & Field Best Practices

Browser multiplayer breaks down when startup blocks waiting for a second tab or when raw 20 Hz WebSocket pose packets visibly stutter on a 60–120 Hz screen. Using the studio's game.net API solves both cleanly:

  1. Solo-First Startup (isHost === true Alone): Immediately run the loop when game.net.players only contains game.net.me. Remote teammates join live through bindAvatar(...) without restarting the level.
  2. Throttled Pose Send + 60 Hz Snapshot Interpolation: Call game.net.setMyPose(...) each step; game.net transmits deltas at 20 Hz and exposes smooth 60 Hz interpolated poses on game.net.poseOf(peer.id) and bound avatars.
  3. Host-Authoritative Claims + Automatic Host Migration: Never mutate shared pickups locally as truth for everyone. Send 'host'-routed events (game.net.send('claim_beacon', { index }, 'host')), let isHost validate once, publish game.net.setState(...), and keep onHostChange ready if Peer 1 disconnects.

Mathematical & Algorithmic Core

  • Circular Yaw Blending: Interpolate headings over shortest angular delta Δpsi ∈ [-π, π): $Δpsi = ((psi_1 - psi_0 + π) bmod 2π) - π, psi(t) = psi_0 + t\,Δpsi$
  • Monotonic Claim Version: Store a monotonically increasing claimed mask or array in game.net.state so late-joining guests converge immediately to current world state without replaying old events.

Engine Implementation

Host-Authoritative Co-Op Beacons & Avatars (Assets/Game/coop-beacons.ts)

import * as THREE from 'three';
import type { Game } from 'ccgd';

export interface BeaconClaimEvent {
  readonly index: number;
}

export interface BeaconFxEvent {
  readonly index: number;
  readonly byName: string;
}

export function setupCoopBeacons(
  game: Game,
  beacons: readonly THREE.Object3D[],
  getPlayerPose: () => { x: number; y: number; z: number; yaw: number; moving: boolean },
  onScoreChange: (scores: Readonly<Record<string, number>>) => void,
): () => void {
  const claimed = new Set<number>();
  const scores: Record<string, number> = {};

  const applyClaimedMask = (indices: unknown): void => {
    if (!Array.isArray(indices)) return;
    claimed.clear();
    for (const raw of indices) {
      if (typeof raw === 'number' && Number.isInteger(raw)) {
        claimed.add(raw);
      }
    }
    for (let i = 0; i < beacons.length; i++) {
      beacons[i].visible = !claimed.has(i);
    }
  };

  // Spawn and 60 Hz-interpolate a capsule avatar per remote peer automatically.
  const unbindAvatars = game.net.bindAvatar((peer) => {
    const group = new THREE.Group();
    const torso = new THREE.Mesh(
      new THREE.CapsuleGeometry(0.32, 0.78, 6, 12),
      new THREE.MeshStandardMaterial({ color: peer.color, roughness: 0.45 }),
    );
    torso.position.y = 0.72;
    torso.castShadow = true;
    group.add(torso);
    return group;
  });

  const unsubState = game.net.onState((state) => {
    applyClaimedMask(state.claimedBeacons);
    if (state.scores && typeof state.scores === 'object') {
      onScoreChange(state.scores as Record<string, number>);
    }
  });

  const unsubClaim = game.net.on<BeaconClaimEvent>('claim_beacon', (data, from) => {
    if (!game.net.isHost) return;
    if (data.index < 0 || data.index >= beacons.length || claimed.has(data.index)) return;

    claimed.add(data.index);
    const key = String(from.id);
    scores[key] = (scores[key] ?? 0) + 1;
    beacons[data.index].visible = false;

    game.net.setState({
      claimedBeacons: [...claimed],
      scores: { ...scores },
    });
    game.net.send('beacon_fx', { index: data.index, byName: from.name }, 'all');
  });

  const unsubFx = game.net.on<BeaconFxEvent>('beacon_fx', () => {
    game.audio.play('pickup', { volume: 0.7 });
  });

  const unsubHost = game.net.onHostChange((isNowHost) => {
    if (isNowHost) {
      // Rehydrate local tracking structures immediately upon promotion
      applyClaimedMask(game.net.getState('claimedBeacons', []));
    }
  });

  game.onUpdate(() => {
    const pose = getPlayerPose();
    game.net.setMyPose({
      x: pose.x,
      y: pose.y,
      z: pose.z,
      yaw: pose.yaw,
      anim: pose.moving ? 'run' : 'idle',
    });
  });

  return () => {
    unbindAvatars();
    unsubState();
    unsubClaim();
    unsubFx();
    unsubHost();
  };
}

Deterministic Two-Peer & Host-Migration Test (Assets/Game/Tests/play/net-coop.test.ts)

import { test } from 'ccgd';

test('remote pose interpolation and host migration keep room state intact', async (t) => {
  const rival = t.game.net.sim.addPeer({ name: 'RIV1' });
  rival.setPose({ x: 3.5, y: 0, z: -2.0, yaw: 0.75 });
  await t.steps(6);

  const interpolated = t.game.net.poseOf(rival.peer.id);
  t.ok(interpolated !== undefined, 'remote peer pose tracked');
  if (interpolated) {
    t.near(interpolated.x, 3.5, 0.05, 'interpolated x matches peer');
  }

  const hostPeer = t.game.net.sim.addPeer({ asHost: true, name: 'HOST' });
  t.eq(t.game.net.isHost, false, 'client yields host role to lower peer id');
  t.game.net.sim.pushHostState({ round: 2 });
  t.eq(t.game.net.getState<number>('round', 0), 2, 'host state replicated');

  t.game.net.sim.dropHost();
  t.eq(t.game.net.isHost, true, 'surviving client promoted to host cleanly');
  void hostPeer;
});

Browser & Bandwidth Guardrails

  • Bounded State Keys: Store compact arrays/objects inside game.net.setState(...) rather than full frame histories so join snapshots fit comfortably in one WebSocket message.
  • Always Test Solo + Drop-In: Verify play tests pass before any sim.addPeer call so the single-player default stays responsive on first paint.

Verification Checklist

  1. Run ccgd mp-check (or net.sim play test) to verify two simulated peers sync state cleanly and survive host departure.
  2. Confirm every setState mutation sits behind an isHost check so guests never overwrite authoritative world state.

Official references

  • Glenn Fiedler (Gaffer on Games — State Synchronization & Snapshot Interpolation)
  • GameCrew Multiplayer Room Protocol Reference

Playable Three.js games made with GameCrew

Launch a real browser build using this engine and inspect its controls or fork its project tree.

More Three.js techniques

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

atmosphere

Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →

Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.

physics

BVH Mesh & Character Capsule Collision in Three.js →

Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.

ai

Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →

Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration