Three.js

This page builds the runners game from Engines and frameworks in 3D with Three.js. It imports shared.ts from that page; read its Connecting and Teardown sections first.

The room’s world is flat, in x and y. The scene puts it on the ground plane: a runner at room (x, y) stands at (x, 0, y) in Three.js, and its angle turns it about the vertical axis.

// arena.ts
import { reloadForNewBuild, RoomClient } from "@irtio/client";
import { joinVoice } from "@irtio/client/voice";
import * as THREE from "three";
import { type Input, Runner, schema, stepper } from "./shared.js";


export function startArena(parent: HTMLElement, roomId: string, show: (status: string) => void) {
  const room = new RoomClient(roomId, { schema });

  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(parent.clientWidth, parent.clientHeight);
  parent.appendChild(renderer.domElement);
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(60, parent.clientWidth / parent.clientHeight, 0.1, 500);
  scene.add(new THREE.HemisphereLight(0xffffff, 0x334455, 2));

  const bodyShape = new THREE.CapsuleGeometry(0.4, 0.8);
  const noseShape = new THREE.BoxGeometry(0.5, 0.15, 0.15);
  const materials = {
    mine: new THREE.MeshStandardMaterial({ color: 0x4cc9f0 }),
    theirs: new THREE.MeshStandardMaterial({ color: 0xf72585 }),
    nose: new THREE.MeshStandardMaterial({ color: 0xffffff }),
  };
  const meshes = new Map<number, THREE.Mesh>();
  show("connecting");

  const listening = new AbortController();
  const signal = listening.signal;
  room.addEventListener("waking", () => show("waking the room"), { signal });
  room.addEventListener("reconnecting", () => show("reconnecting"), { signal });
  room.addEventListener("open", () => show(""), { signal });
  room.addEventListener(
    "close",
    ({ error }) => {
      if (error?.name === "VersionError") reloadForNewBuild();
      else show(error?.message ?? "");
    },
    { signal },
  );

  const offs = [
    room.entities.onEnter(Runner, (r) => {
      const mesh = new THREE.Mesh(bodyShape, r.owner === room.player ? materials.mine : materials.theirs);
      const nose = new THREE.Mesh(noseShape, materials.nose);
      nose.position.set(0.5, 0.3, 0);
      mesh.add(nose);
      mesh.position.set(r.x, 0.8, r.y);
      mesh.rotation.y = -r.angle;
      scene.add(mesh);
      meshes.set(r.id, mesh);
    }),
    room.entities.onLeave(Runner, (r) => {
      const mesh = meshes.get(r.id);
      if (mesh) scene.remove(mesh);
      meshes.delete(r.id);
    }),
  ];

  const keys = new Set<string>();
  const down = (e: KeyboardEvent) => keys.add(e.key);
  const up = (e: KeyboardEvent) => keys.delete(e.key);
  addEventListener("keydown", down);
  addEventListener("keyup", up);

  const me = room.predict(stepper, {
    find: (r) => [...r.entities.all(Runner)].find((e) => e.owner === r.player),
    sample: (): Input => ({
      dx: (keys.has("ArrowRight") ? 1 : 0) - (keys.has("ArrowLeft") ? 1 : 0),
      dy: (keys.has("ArrowDown") ? 1 : 0) - (keys.has("ArrowUp") ? 1 : 0),
    }),
  });
  const others = room.interpolate(Runner, ["x", "y", "angle"]);

  const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
  const raycaster = new THREE.Raycaster();
  const pointer = new THREE.Vector2();
  const hit = new THREE.Vector3();
  const aim = (e: PointerEvent) => {
    const rect = renderer.domElement.getBoundingClientRect();
    pointer.set(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
    raycaster.setFromCamera(pointer, camera);
    if (!raycaster.ray.intersectPlane(ground, hit)) return;
    const at = me.render(["x", "y"]);
    for (const r of room.entities.mine(Runner)) {
      r.angle = Math.atan2(hit.z - at.y, hit.x - at.x);
      const mesh = meshes.get(r.id);
      if (mesh) mesh.rotation.y = -r.angle;
    }
  };
  renderer.domElement.addEventListener("pointermove", aim);

  const voice = joinVoice(room, {
    position(player) {
      const r = [...room.entities.all(Runner)].find((e) => e.owner === player);
      return r && { x: r.x, y: 0, z: r.y };
    },
    spatial: true,
    range: 20,
  });

  renderer.setAnimationLoop(() => {
    const local = me.render(["x", "y"]);
    for (const r of room.entities.all(Runner)) {
      const mesh = meshes.get(r.id);
      if (!mesh) continue;
      if (r.owner === room.player) {
        if (!Number.isNaN(local.x)) mesh.position.set(local.x, 0.8, local.y);
        continue;
      }
      const at = others.get(r);
      mesh.position.set(at.x, 0.8, at.y);
      mesh.rotation.y = -at.angle;
    }
    if (!Number.isNaN(local.x)) {
      camera.position.set(local.x, 14, local.y + 10);
      camera.lookAt(local.x, 0, local.y);
    }
    renderer.render(scene, camera);
  });

  const stop = async () => {
    listening.abort();
    for (const off of offs) off();
    renderer.setAnimationLoop(null);
    renderer.domElement.removeEventListener("pointermove", aim);
    removeEventListener("keydown", down);
    removeEventListener("keyup", up);
    me.stop();
    room.close();
    await voice.disconnect();
    for (const mesh of meshes.values()) scene.remove(mesh);
    meshes.clear();
    bodyShape.dispose();
    noseShape.dispose();
    for (const m of Object.values(materials)) m.dispose();
    renderer.dispose();
    renderer.domElement.remove();
  };
  return { room, voice, stop };
}

And the page that runs it, with a talk button and a call:

// main.ts
import { IrtError } from "@irtio/client";
import { startArena } from "./arena.js";

const status = document.querySelector("#status")!;
const arena = startArena(document.querySelector("#game")!, new URLSearchParams(location.search).get("room") ?? "arena", (s) => {
  status.textContent = s;
});

// Browsers grant the microphone only from a user gesture.
document.querySelector("#talk")!.addEventListener("click", () => void arena.voice.enableMic());
document.querySelector("#buy")!.addEventListener("click", async () => {
  if (arena.room.readyState !== "open") return;
  try {
    const { coins } = await arena.room.calls.buy({ item: "dash" });
    status.textContent = `${coins} coins left`;
  } catch (e) {
    if (e instanceof IrtError) status.textContent = e.message;
    else throw e;
  }
});
document.querySelector("#leave")!.addEventListener("click", () => void arena.stop());

How it fits together:

  • One animation loop. setAnimationLoop draws every frame: remote runners at their interpolated position and heading, the local runner at its predicted position, and the camera following the predicted position, so the camera never lags the player.
  • Aim from a raycast. The pointer’s ray meets the ground plane, and the angle from the predicted position to that point is written to the owned runner. The local mesh turns at once; other clients interpolate the new angle a state update later. It’s an angle field, so a runner turning past west, where atan2 jumps from π to -π, turns the short way.
  • Spatial voice. spatial: true pans speakers with Web Audio. The positions given to joinVoice are room positions on the Three.js axes, (x, 0, y), and the Web Audio listener faces -z with +x to its right, as the camera does, so a speaker on the right of the screen is heard on the right.
  • The buy button checks readyState. A call throws before the client is first ready and rejects while it reconnects, so the button does nothing until the room is open.
  • Teardown frees GPU memory. Removing a mesh from the scene doesn’t free its geometry or material; the shared ones are disposed once, in stop, with the renderer.

Resize handling is left out: on resize, set camera.aspect, call camera.updateProjectionMatrix() and renderer.setSize(...) as in any Three.js app.

Full 3D rotations

For something that turns about more than one axis, such as a ship or a thrown crate, declare its rotation as one quat field. Its value is { x, y, z, w }, which quaternion.copy takes as is, and a write takes a THREE.Quaternion:

// ships.ts
import { defineSchema, entity, type RoomClient } from "@irtio/client";
import * as THREE from "three";

export const Ship = entity("ship", { owner: "string", x: "f32", y: "f32", z: "f32", rot: "quat" }, { writable: ["rot"] });
export const schema = defineSchema({ entities: [Ship] });

export function drawShips(room: RoomClient, meshes: Map<number, THREE.Object3D>) {
  const ships = room.interpolate(Ship, ["x", "y", "z", "rot"]);
  return () => {
    for (const ship of room.entities.all(Ship)) {
      const at = ships.get(ship);
      meshes.get(ship.id)?.position.set(at.x, at.y, at.z);
      meshes.get(ship.id)?.quaternion.copy(at.rot);
    }
  };
}

export function steer(room: RoomClient, mesh: THREE.Object3D) {
  for (const ship of room.entities.mine(Ship)) ship.rot = mesh.quaternion;
}

A quaternion and its negation are the same rotation, and a physics engine can switch between them from one step to the next. interpolate blends a quat on the same side as the last one, by normalised lerp, so the mesh never spins the long way round, which four f32 fields qx..qw lerped one by one can. The room keeps a quat at length 1 and refuses one of length 0.

Common mistakes

  • New geometry and material per runner. A runner enters again on every reconnect, so per-entity GPU resources pile up unless each onLeave disposes them. Share them, as above.
  • Driving the camera from me.entity. It jumps on every correction; render smooths them.
  • Mixing up the axes. The room’s y is the scene’s z. Map in one place, in both directions: positions, aim and voice.