Ask a player's game
The server has no physics and no camera. Get answers from a player's game with a request and reply over events, matched by ID, with a timeout, and checked against who was asked.
The server knows where everybody is, but it has no world to look at: no collision, no line of sight, no camera. Some questions can only be answered inside a player’s game. “Can this player see that one?” is a raycast through real geometry. “Show me what they see” is a camera. This page builds both the way the default gamemode does, starting with the pattern they share.
Why not Messages?
Section titled “Why not Messages?”Messages.request already does request and reply, but it joins resources on the same side: one
server resource asking another. There is nothing that awaits an answer from a client, so you build
it out of the two events that do cross:
| Direction | Call |
|---|---|
| Server to one player | player.emit(name, json) |
| That player back to the server | Events.emitServer(name, payload), heard by Events.onClient |
What makes a pair of events behave like a function call is three small things: an ID on every request so replies can be matched, a timeout so a player who never answers does not hang the caller, and a check that the reply came from the player who was asked.
The server side
Section titled “The server side”interface Point { x: number; y: number; z: number;}
export interface RaycastHit { hit: boolean; position: Point; normal: Point; fraction: number; ref: number | null; entity: number | null;}
const kTimeoutMs = 3000;
const pending = new Map<number, { player: number; resolve: (hit: RaycastHit | null) => void }>();let nextId = 1;
/** Casts a ray in `player`'s game. Null when it cannot, or does not answer in time. */export function askRaycast(player: Player, from: Point, to: Point): Promise<RaycastHit | null> { const id = nextId++; return new Promise((resolve) => { pending.set(id, { player: player.id, resolve }); setTimeout(() => { // Still pending: they left, are loading, or ignored it. if (pending.delete(id)) resolve(null); }, kTimeoutMs); player.emit("raycast:cast", JSON.stringify({ id, from, to })); });}
Events.onClient("raycast:answer", (player: Player, payload?: unknown) => { const answer = payload as { id?: unknown; result?: unknown } | undefined; if (typeof answer?.id !== "number") return;
const waiting = pending.get(answer.id); // Only the player who was asked may answer. Anyone else is guessing IDs. if (waiting === undefined || waiting.player !== player.id) return;
pending.delete(answer.id); waiting.resolve((answer.result ?? null) as RaycastHit | null);});pending.delete returning true is what keeps the timeout and the answer from both resolving the
same promise: whichever comes first removes the entry, and the other finds nothing to do.
The client side
Section titled “The client side”The client answers with whatever its own API returns. World.raycast strikes the game’s real
collision, and reports the network ID of a player or NPC it hit:
// clientinterface CastRequest { id: number; from: { x: number; y: number; z: number }; to: { x: number; y: number; z: number };}
Events.on("raycast:cast", (payload: unknown) => { const request = payload as CastRequest; const from = new Vector3(request.from.x, request.from.y, request.from.z); const to = new Vector3(request.to.x, request.to.y, request.to.z); const result = World.raycast(from, to); Events.emitServer("raycast:answer", { id: request.id, result });});The payload arrives already parsed from JSON, so request is a plain object. Vector3 values become
plain { x, y, z } objects on the way, which is why both sides rebuild or describe them as Point.
Using it: line of sight
Section titled “Using it: line of sight”With the plumbing in place, a /los command reads like ordinary async code. The ray starts at the
sender’s eyes and ends at the target’s chest:
import { askRaycast } from "./raycast.js";
const kEyeHeight = 120;const kChestHeight = 90;
Events.on("playerCommand", async (player: Player, command: string, args: string[]) => { if (command !== "los") return; const target = Player.all().find((p) => p.nickname === args[0]); if (target === undefined || target.id === player.id) return;
const from = { x: player.position.x, y: player.position.y, z: player.position.z + kEyeHeight }; const to = { x: target.position.x, y: target.position.y, z: target.position.z + kChestHeight }; const hit = await askRaycast(player, from, to);
let verdict: string; if (hit === null) verdict = "Your game did not answer."; else if (hit.hit && hit.entity === target.id) verdict = `You see ${target.nickname}.`; else if (hit.hit) verdict = `Something blocks ${target.nickname}.`; else verdict = `Nothing between you and ${target.nickname}.`; Chat.sendToPlayer(player, verdict, { author: "LOS" });});hit.entity is the same ID the server uses (player.id, npc.id), so comparing it to the target
needs no translation. The ray passes over the caster’s own body by default.
Spectating
Section titled “Spectating”A spectator mode is the same split in a different shape: the server decides who watches whom and keeps the spectator near enough, and the spectator’s game moves its camera.
The client side only needs to follow orders. Camera.setTarget makes the camera follow another body
in third person, and returns false when that body is not loaded yet, which it often will not be
right after a teleport. So retry for a while:
// clientlet retry: number | null = null;
function stopRetrying(): void { if (retry !== null) clearInterval(retry); retry = null;}
Events.on("spectate:target", (payload: unknown) => { stopRetrying(); const target = typeof payload === "number" ? payload : null; if (target === null) { Camera.setTarget(null); // back to our own body return; } if (Camera.setTarget(target)) return;
let tries = 0; retry = setInterval(() => { tries += 1; if (Camera.setTarget(target) || tries >= 30) stopRetrying(); }, 500);});The server hides the spectator and parks them above the target. Their own body has to stay within streaming range, or the target’s body unloads from their game and the camera falls back:
interface Watch { target: Player; home: Vector3; homeHeading: number; homeSpace: { worldSpace: number } | { interiorCell: number };}
const watching = new Map<number, Watch>();const kFollowDistance = 1500;
function spaceOf(player: Player): { worldSpace: number } | { interiorCell: number } { const space = player.getSpace(); return space !== null && space.interiorCell !== 0 ? { interiorCell: space.interiorCell } : { worldSpace: space?.worldSpace || 0x3c };}
const above = (target: Player): Vector3 => new Vector3(target.position.x, target.position.y, target.position.z + 200);
export function startWatching(spectator: Player, target: Player): void { watching.set(spectator.id, { target, home: spectator.position.clone(), homeHeading: spectator.heading, homeSpace: spaceOf(spectator), }); spectator.setAlpha(0); // nobody sees them spectator.setInvulnerable(true); // nobody hurts them spectator.setRestrained(true); // they do not wander off spectator.teleport(above(target), target.heading, spaceOf(target)); spectator.emit("spectate:target", JSON.stringify(target.id));}
export function stopWatching(spectator: Player): void { const watch = watching.get(spectator.id); if (watch === undefined) return; watching.delete(spectator.id); spectator.emit("spectate:target", JSON.stringify(null)); spectator.teleport(watch.home, watch.homeHeading, watch.homeSpace); spectator.setRestrained(false); spectator.setInvulnerable(false); spectator.setAlpha(1);}
// Keep each spectator near their target as it moves.setInterval(() => { for (const [id, watch] of watching) { const spectator = Player.getById(id); if (spectator === null) { watching.delete(id); continue; } if (spectator.position.distance(watch.target.position) > kFollowDistance) { spectator.teleport(above(watch.target), watch.target.heading, spaceOf(watch.target)); spectator.emit("spectate:target", JSON.stringify(watch.target.id)); } }}, 3000);
Events.on("playerDisconnect", (player: Player) => { watching.delete(player.id); // Anyone watching the player who left goes home. for (const [id, watch] of watching) { if (watch.target.id !== player.id) continue; const spectator = Player.getById(id); if (spectator !== null) stopWatching(spectator); }});spectator.position.clone() matters: position is the live vector, and storing it directly would
store “wherever they are now”, which after the teleport is above the target.
Related
Section titled “Related”- Write your first resource: the event bridge, and how payloads are encoded.
- Settlement terminal: the same trust boundary, between a browser page and the server.