Phaser

This page builds the runners game from Engines and frameworks as a Phaser 3 scene. It imports shared.ts from that page; read its Connecting and Teardown sections first.

The scene owns one RoomClient: it connects in create, draws in update and leaves on the scene’s shutdown event, which Phaser emits when the scene stops or restarts.

// arena-scene.ts
import { IrtError, reloadForNewBuild, RoomClient } from "@irtio/client";
import { joinVoice, type Voice } from "@irtio/client/voice";
import Phaser from "phaser";
import { type Input, Runner, schema, stepper, Wallet } from "./shared.js";

// Pixels per world unit.
const PX = 32;

interface Sprite {
  body: Phaser.GameObjects.Container;
  nose: Phaser.GameObjects.Rectangle;
}

export class ArenaScene extends Phaser.Scene {
  private roomId = "";
  private draw = () => {};

  constructor() {
    super("arena");
  }

  init(data: { room: string }) {
    this.roomId = data.room;
  }

  create() {
    const room = new RoomClient(this.roomId, { schema });
    const sprites = new Map<number, Sprite>();
    const status = this.add.text(8, 8, "connecting");
    const wallet = this.add.text(8, 32, "");
    let voice: Voice | undefined;

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

    const offs = [
      room.entities.onEnter(Runner, (r) => {
        const color = r.owner === room.player ? 0x4cc9f0 : 0xf72585;
        const nose = this.add.rectangle(0, 0, 18, 4, 0xffffff).setOrigin(0, 0.5).setRotation(r.angle);
        const body = this.add.container(r.x * PX, r.y * PX, [this.add.circle(0, 0, 12, color), nose]);
        sprites.set(r.id, { body, nose });
      }),
      room.entities.onChange(Runner, (r, changed) => {
        if (changed.includes("angle")) sprites.get(r.id)?.nose.setRotation(r.angle);
      }),
      room.entities.onLeave(Runner, (r) => {
        sprites.get(r.id)?.body.destroy();
        sprites.delete(r.id);
      }),
      room.entities.onChange(Wallet, (w) => wallet.setText(`${w.coins} coins`)),
    ];

    const keys = this.input.keyboard!.createCursorKeys();
    const me = room.predict(stepper, {
      find: (r) => [...r.entities.all(Runner)].find((e) => e.owner === r.player),
      sample: (): Input => ({
        dx: (keys.right.isDown ? 1 : 0) - (keys.left.isDown ? 1 : 0),
        dy: (keys.down.isDown ? 1 : 0) - (keys.up.isDown ? 1 : 0),
      }),
    });
    const others = room.interpolate(Runner, ["x", "y"]);

    const aim = (pointer: Phaser.Input.Pointer) => {
      const at = me.render(["x", "y"]);
      for (const r of room.entities.mine(Runner)) {
        r.angle = Math.atan2(pointer.worldY - at.y * PX, pointer.worldX - at.x * PX);
        sprites.get(r.id)?.nose.setRotation(r.angle);
      }
    };
    this.input.on("pointermove", aim);

    this.draw = () => {
      const local = me.render(["x", "y"]);
      for (const r of room.entities.all(Runner)) {
        const at = r.owner === room.player ? local : others.get(r);
        if (!Number.isNaN(at.x)) sprites.get(r.id)?.body.setPosition(at.x * PX, at.y * PX);
      }
    };

    room.ready.then(
      () => {
        status.setText("");
        wallet.setText(`${room.private!.coins} coins`);
        voice = joinVoice(room, {
          position(player) {
            const r = [...room.entities.all(Runner)].find((e) => e.owner === player);
            return r && { x: r.x, y: r.y };
          },
          range: 12,
        });
        this.add.text(8, 56, "[ talk ]").setInteractive().on("pointerdown", () => void voice?.enableMic());
        this.add.text(80, 56, "[ buy dash ]").setInteractive().on("pointerdown", () => void buy());
      },
      // A failed connection has already been reported by the close listener.
      () => {},
    );

    const buy = async () => {
      try {
        const { coins } = await room.calls.buy({ item: "dash" });
        wallet.setText(`${coins} coins`);
      } catch (e) {
        if (e instanceof IrtError) status.setText(e.message);
        else throw e;
      }
    };

    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () => {
      listening.abort();
      for (const off of offs) off();
      this.input.off("pointermove", aim);
      me.stop();
      void voice?.disconnect();
      room.close();
      sprites.clear();
      this.draw = () => {};
    });
  }

  update() {
    this.draw();
  }
}

Start it with the room ID your lobby picked:

// main.ts
import Phaser from "phaser";
import { ArenaScene } from "./arena-scene.js";

const game = new Phaser.Game({ type: Phaser.AUTO, width: 960, height: 640 });
// Added here rather than in the config, so that it starts with its room ID.
game.scene.add("arena", ArenaScene, true, { room: new URLSearchParams(location.search).get("room") ?? "arena" });

How it fits together:

  • create is synchronous. Phaser doesn’t wait for a promise from create, so the scene builds its listeners at once and continues in room.ready.then(...). The buttons that call the room appear only then, because calls throw until the client is ready.
  • update draws. It runs every frame, between Phaser’s own updates and its render. Every runner but the player’s is interpolated; the player’s is predicted.
  • The local nose turns at once. The aim handler writes angle on the owned runner and rotates its sprite itself, since onChange doesn’t fire for the player’s own writable fields. The client sends the writes once per room tick, however often the pointer moves.
  • The wallet is private state. room.private is an entity of the schema’s private kind, so onChange(Wallet, ...) follows it, and the reply to buy updates the label before the state update arrives.
  • Shutdown undoes create. Phaser destroys the scene’s game objects itself; the scene removes IRT listeners first, aborting their signal, so the close event that close() fires doesn’t reach a destroyed label.

Browsers pause requestAnimationFrame, and with it Phaser’s update, in background tabs. The IRT client keeps applying state updates, so the scene is current when the player comes back.

Common mistakes

  • An async create(). Phaser calls update before the promise settles, and an error in it is lost. Keep create synchronous.
  • Destroying game objects in onLeave after shutdown. Remove the room listeners in the shutdown handler, before close().
  • Reading pointer input in sample. Aim isn’t an input: it’s a writable field, so write it from the pointer event and keep sample for what the stepper simulates.
  • No shutdown handler. scene.restart() then opens a second client as the same player, and the router closes the first with 4012 while its listeners still draw into the old scene.