A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(examples): multiplayer-arena — the replication pattern in ~100 lines
esengine0c014eb31011
diff --git a/examples/multiplayer-arena/README.md b/examples/multiplayer-arena/README.mdnew file mode 100644index 000000000..1d40f644c--- /dev/null+++ b/examples/multiplayer-arena/README.md@@ -0,0 +1,27 @@+# Multiplayer Arena++Server-authoritative multiplayer in ~100 lines: each player steers a colored+pawn inside an arena, replicated to every other player.++## Run it++Open the project in the editor, then pick **2 Players (Listen Server)** (or 3/4)+from the Play-mode dropdown and press **Play**. Player 1 runs in the usual Game+view as the authority; each extra player gets its own `Game P#` tab. Click a+tab to give that player keyboard focus — WASD / arrows to move.++Plain **Single Player** Play works too: the same systems run offline.++## What it shows++- `Replicated` marks an entity for replication — the spawn carries every+ component (the sprite color included), and Transform's built-in `replicated`+ annotation streams the pose as binary deltas with snapshot interpolation.+- The authority is the only simulator: `movePawnsSystem` integrates every pawn,+ reading the local keyboard for the host and `server.inputOf(connection)` for+ remote players (`Replicated.owner` routes input to its pawn).+- Clients run one system: sample the keyboard, `client.sendInput(...)` once per+ fixed tick. Everything they see — their own pawn included — is replicated,+ authoritative state.+- The same gameplay code ships unchanged against a real WebSocket server+ (`esengine/node` + `createHeadlessApp`).diff --git a/examples/multiplayer-arena/assets/scenes/main.esscene b/examples/multiplayer-arena/assets/scenes/main.esscenenew file mode 100644index 000000000..192c2de2b--- /dev/null+++ b/examples/multiplayer-arena/assets/scenes/main.esscene@@ -0,0 +1,72 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 340, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Wall Top",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 310, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 920, "y": 16 }, "color": { "r": 0.22, "g": 0.26, "b": 0.36, "a": 1 }, "layer": 1 } }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Wall Bottom",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -310, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 920, "y": 16 }, "color": { "r": 0.22, "g": 0.26, "b": 0.36, "a": 1 }, "layer": 1 } }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "Wall Left",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": -452, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 16, "y": 604 }, "color": { "r": 0.22, "g": 0.26, "b": 0.36, "a": 1 }, "layer": 1 } }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "Wall Right",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 452, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 16, "y": 604 }, "color": { "r": 0.22, "g": 0.26, "b": 0.36, "a": 1 }, "layer": 1 } }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "Center Obstacle",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 90, "y": 90 }, "color": { "r": 0.16, "g": 0.19, "b": 0.27, "a": 1 }, "layer": 1 } }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/multiplayer-arena/project.esproject b/examples/multiplayer-arena/project.esprojectnew file mode 100644index 000000000..d2fb07490--- /dev/null+++ b/examples/multiplayer-arena/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Multiplayer Arena",+ "description": "Server-authoritative multiplayer: each player steers a replicated pawn. Pick '2 Players' in the Play dropdown to run a listen server + client side by side.",+ "tag": "Networking",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 960,+ "height": 640+ },+ "spineVersion": "none"+}diff --git a/examples/multiplayer-arena/src/components.ts b/examples/multiplayer-arena/src/components.tsnew file mode 100644index 000000000..12f05c0ee--- /dev/null+++ b/examples/multiplayer-arena/src/components.ts@@ -0,0 +1,11 @@+import { defineComponent } from 'esengine';++/**+ * A player-steered pawn. `player` is the owning connection id (0 = the host+ * player). The pawn's pose replicates through Transform's built-in `replicated`+ * annotation; `player` rides the spawn payload, so ghosts know who they are.+ */+export const Pawn = defineComponent('Pawn', {+ player: 0,+ speed: 260,+});diff --git a/examples/multiplayer-arena/src/main.ts b/examples/multiplayer-arena/src/main.tsnew file mode 100644index 000000000..97f4bd674--- /dev/null+++ b/examples/multiplayer-arena/src/main.ts@@ -0,0 +1,10 @@+import { addSystemToSchedule, Schedule } from 'esengine';+import { provisionPawnsSystem, movePawnsSystem, sendInputSystem } from './net';++// Netcode lives on the fixed timestep (the replication cadence): the authority+// provisions + simulates there, the client uplinks input there. All three+// systems self-gate on the Net role, so the same code runs as the listen+// server, a client, or plain offline single-player.+addSystemToSchedule(Schedule.FixedUpdate, provisionPawnsSystem);+addSystemToSchedule(Schedule.FixedUpdate, movePawnsSystem);+addSystemToSchedule(Schedule.FixedUpdate, sendInputSystem);diff --git a/examples/multiplayer-arena/src/net.ts b/examples/multiplayer-arena/src/net.tsnew file mode 100644index 000000000..39df338b5--- /dev/null+++ b/examples/multiplayer-arena/src/net.ts@@ -0,0 +1,96 @@+import {+ defineSystem, Query, Mut, Res, GetWorld,+ Time, Input, Net, Replicated, Transform, Sprite,+ type World, type InputState,+} from 'esengine';+import { Pawn } from './components';++// Arena bounds the authority clamps pawns to (matches the scene's walls).+const BOUND_X = 420;+const BOUND_Y = 278;++const PLAYER_COLORS = [+ { r: 0.35, g: 0.85, b: 1.0, a: 1 }, // host — cyan+ { r: 1.0, g: 0.55, b: 0.35, a: 1 }, // player 2 — orange+ { r: 0.55, g: 1.0, b: 0.45, a: 1 }, // player 3 — green+ { r: 0.95, g: 0.5, b: 1.0, a: 1 }, // player 4 — violet+];++function readMove(input: InputState): { x: number; y: number } {+ let x = 0;+ let y = 0;+ if (input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) y += 1;+ if (input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) y -= 1;+ if (input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) x -= 1;+ if (input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) x += 1;+ const len = Math.hypot(x, y);+ return len > 0 ? { x: x / len, y: y / len } : { x: 0, y: 0 };+}++function spawnPawn(world: World, player: number): void {+ const slot = PLAYER_COLORS[player % PLAYER_COLORS.length];+ const e = world.spawn(`Pawn P${player + 1}`);+ world.insert(e, Transform, { position: { x: -150 + player * 100, y: -180, z: 0 } });+ world.insert(e, Sprite, { size: { x: 36, y: 36 }, color: slot, layer: 2 });+ world.insert(e, Pawn, { player });+ // Marking it Replicated is ALL it takes: the entity spawns on every client+ // (full component payload — sprite color included), its annotated Transform+ // pose streams as deltas, and `owner` routes that connection's input to it.+ world.insert(e, Replicated, { owner: player });+}++/**+ * Authority-side player provisioning: the host pawn always exists (so plain+ * single-player Play works too), and each handshaken client connection gets a+ * pawn. Stateless — derives what exists from the World each tick.+ */+export const provisionPawnsSystem = defineSystem(+ [GetWorld(), Res(Net)],+ (world, net) => {+ if (net.role === 'client') return;+ const have = new Set<number>();+ for (const e of world.getEntitiesWithComponents([Pawn])) {+ have.add((world.tryGet(e, Pawn) as { player: number }).player);+ }+ if (!have.has(0)) spawnPawn(world, 0);+ if (net.server) {+ for (const id of net.server.clientIds) {+ if (!have.has(id)) spawnPawn(world, id);+ }+ }+ },+ { name: 'ProvisionPawnsSystem' },+);++/**+ * Authority-side movement: one rule for everyone. The host pawn reads the local+ * keyboard; remote pawns read their connection's uplinked input. Clients never+ * run this — their view of every pawn (their own included) is the replicated,+ * interpolated authoritative state.+ */+export const movePawnsSystem = defineSystem(+ [Query(Mut(Transform), Pawn, Replicated), Res(Net), Res(Input), Res(Time)],+ (query, net, input, time) => {+ if (net.role === 'client') return;+ for (const [, transform, pawn, repl] of query) {+ const move = repl.owner === 0+ ? readMove(input)+ : ((net.server?.inputOf(repl.owner)?.actions.move as { x: number; y: number } | undefined) ?? { x: 0, y: 0 });+ if (move.x === 0 && move.y === 0) continue;+ const p = transform.position;+ p.x = Math.min(BOUND_X, Math.max(-BOUND_X, p.x + move.x * pawn.speed * time.fixedDelta));+ p.y = Math.min(BOUND_Y, Math.max(-BOUND_Y, p.y + move.y * pawn.speed * time.fixedDelta));+ }+ },+ { name: 'MovePawnsSystem' },+);++/** Client-side input uplink: one command per fixed tick, keyboard → server. */+export const sendInputSystem = defineSystem(+ [Res(Net), Res(Input)],+ (net, input) => {+ if (net.role !== 'client') return;+ net.client?.sendInput({ move: readMove(input) });+ },+ { name: 'SendInputSystem' },+);diff --git a/examples/multiplayer-arena/thumbnail.png b/examples/multiplayer-arena/thumbnail.pngnew file mode 100644index 000000000..6dda41d0dBinary files /dev/null and b/examples/multiplayer-arena/thumbnail.png differdiff --git a/examples/multiplayer-arena/tsconfig.json b/examples/multiplayer-arena/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/multiplayer-arena/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex f7c51ea0f..58490ea77 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -91,6 +91,16 @@ export class ReplicationServer {return this.connections_.size;}+ /** Ready (handshaken) connection ids. Gameplay polls this each fixed tick+ * to provision/retire per-player entities — no callback wiring needed. */+ get clientIds(): number[] {+ const out: number[] = [];+ for (const c of this.connections_.values()) {+ if (c.ready) out.push(c.id);+ }+ return out;+ }+private get refs_(): EntityRefMap {return {toWire: (entity) => this.netIds_.netIdOf(entity as Entity) ?? 0,