Example of a Room implementations

This example demonstrates an entire room implementing the onCreate, onJoin and onMessage methods.

MyRoom.ts
import { Room, Client } from "colyseus";
import { Schema, MapSchema, type } from "@colyseus/schema";
 
// State sync: Player structure
export class Player extends Schema {
  @type("number") x: number = 0.11;
  @type("number") y: number = 2.22;
}
 
// State sync: State structure
export class State extends Schema {
  @type({ map: Player }) players = new MapSchema<Player>();
}
 
export class GameRoom extends Room<State> {
  // initialize empty room state
  state = new State();
 
  // Colyseus will invoke when creating the room instance
  onCreate(options: any) {
    // Called every time this room receives a "move" message
    this.onMessage("move", (client, data) => {
      const player = this.state.players.get(client.sessionId);
      player.x += data.x;
      player.y += data.y;
      console.log(client.sessionId + " at, x: " + player.x, "y: " + player.y);
    });
  }
 
  // Called every time a client joins
  onJoin(client: Client, options: any) {
    this.state.players.set(client.sessionId, new Player());
  }
}
Last updated on