EARTH GAMESKORAI HOZZÁFÉRÉS
Home›Developers›API reference
API REFERENCEv1173 CALLS · 15 EVENTS

Earth Games API reference

Rules scripts interact with the world through eg.namespace.name(…) and exported event handlers. Generated directly from the platform's live API table.

A player argument takes a Player object or its string id. A point is { lat, lon }. Calls marked async return a Promise and resolve a few milliseconds later — await them. Every entry shows runnable JS alongside what players actually see in the 3D world.

Events

Export the handlers your game needs from server.js: export default { onStart() { … } }. Any handler may be async.

onLoad(saved: { [key: string]: any }, info: { version: string | null, savedAt: number | null, fresh: boolean })
event#

Persistent games only, before onStart: everything this world saved with saves.set. "fresh" is true for a brand-new world. "version" is the version of your game that last saved it, so an update can convert old saves here.

example.js
js
if (saved && saved.day) eg.state.day = saved.day;
if (info.fresh) eg.state.day = 1;
What happens in gameresult

Runs before `onStart` in persistent worlds, restoring saved state across server restarts or new sessions.

World LoadedRestored day 14 from persistent save
onStart()
event#

The game started (or restarted after the server did). Set things up here.

example.js
js
eg.teams.define([{ id: 'red', color: 'red' }, { id: 'blue', color: 'blue' }]);
eg.instance.setPhase('lobby');
What happens in gamehud

Initializes teams, spawners, combat rules, and lobby phase once as soon as the instance boots.

Game Booted
PHASE: LOBBY
onPlayerJoin(player, info: { rejoined: boolean })
event#

A player entered the game. `rejoined` is true when they came back after a dropped connection in time to keep their place.

example.js
js
eg.ui.toast(player, info.rejoined ? 'Welcome back!' : 'Welcome!', 'good');
eg.ui.hud(player, [{ type: 'title', text: 'Ready' }]);
What happens in gametoast

Fires each time a player enters (or reconnects inside the rejoin window) so you can orient them and send their initial HUD.

Welcome back!
onPlayerAway(player)
event#

A player's connection dropped and their place is being held for a while (manifest player.rejoinS). Pause what they were doing.

example.js
js
eg.players.setData(player, 'pausedAt', eg.world.now());
eg.ui.toast(null, eg.t('{name} disconnected (seat held).', { name: player }), 'warn');
What happens in gametoast

Alerts your script when a player drops connection during a `rejoinS` grace window so you can pause timers until they return.

Mira disconnected (seat held).
onPlayerLeave(player, reason: 'left' | 'disconnected' | 'timeout' | 'closed')
event#

A player is gone from the game for good.

example.js
js
eg.ui.toast(null, eg.t('{name} left ({reason}).', { name: player, reason: 'left' }));
What happens in gametoast

Notifies your script when a player exits for good so you can reassign roles, rebalance teams, or clean up entities.

Mira left (left).
onPlayerArea(player, area: { id: string, center: point })
event#

A player came into a new area (about 1.5 km squares), including the one they start in. Use it to put things where players actually are.

example.js
js
const shops = await eg.world.placesNear(area.center, { kinds: ['shop'], max: 2, seed: area.id });
for (const s of shops) eg.entities.add({ id: 's-' + s.id, kind: 'zone', at: s, label: s.name, trigger: {} });
What happens in gameworld

Fires whenever a player steps or drives into a new ~1.5 km map square, letting games populate real places endlessly anywhere on Earth.

NEW 1.5 km CELL Dynamic Cell Population Generates nearby quests wherever players travel
onPlayerMode(player, change: { from: string, to: string })
event#

A player switched how they are getting around (for instance walk to drive, or drive to walk).

example.js
js
if (change.to === 'fly') {
  eg.ui.toast(player, 'No helicopters allowed in ground zones!', 'warn');
}
What happens in gametoast

Triggers instantly when a player switches travel mode (`walk`, `drive`, `fly`, etc.) so scripts can swap HUDs or enforce rules.

No helicopters allowed in ground zones!
onZone(player, entityId: string, what: 'enter' | 'leave' | 'dwell')
event#

A player entered or left a zone with a trigger, or stayed in it slowly enough for long enough (dwell).

example.js
js
if (what === 'dwell' && entityId === 'capture') {
  eg.ui.toast(player, 'Zone captured!', 'good');
  eg.fx.confetti(player);
}
What happens in gameworld

Fires when a player walks or drives into (`enter`), exits (`leave`), or holds inside (`dwell`) a trigger zone.

ZONE DWELL Zone Captured! Confetti bursts around player inside capture ring
onInteract(player, entityId: string)
event#

A player pressed F at an entity with `interact`.

example.js
js
if (entityId === 'terminal') {
  const ok = await eg.ui.confirm(player, { title: 'Hack Terminal?', body: 'Alerts nearby guards.' });
  if (ok) eg.ui.toast(player, 'Hacking...', 'warn');
}
What happens in gameprompt

Fires when a player walks up to an entity with `interact` and presses `F` (or taps the interact prompt on touch).

F INTERACT Hack Terminal?

Alerts nearby guards.

CancelConfirm
onUi(player, what: { from: 'menu' | 'card' | 'hud' | 'action' | 'window', id: string, item?: string, tab?: string, button?: string, closed?: boolean })
event#

A player chose something: a menu item or tab, a button on a card, HUD or window, closing a window, or one of the game's own actions (manifest `actions`, such as a key).

example.js
js
if (what.from === 'window' && what.id === 'shop' && what.button === 'heal') {
  eg.combat.heal(player, 50);
  eg.ui.toast(player, 'Healed +50 HP!', 'good');
}
What happens in gamewindow

Handles button clicks, tab switches, menu item choices, window closes, and custom manifest hotkeys (`KeyH`, `J`).

ShopField Station
✕
Heal (+50 HP)
onPlayerDamaged(player, hit: { amount: number, hp: number, why: 'npc' | 'player' | 'blast' | string, by?: string, npc?: number, kind?: string, weapon?: string })
event#

A player lost health. `by` is the id of the player responsible, `npc` the character.

example.js
js
if (hit.why === 'npc') {
  eg.ui.toast(player, eg.t('Hit for {n}!', { n: hit.amount }), 'warn');
}
What happens in gametoast

Reports every point of damage taken (from NPCs, rival players, blasts, or script damage) along with remaining HP.

Hit for 12!
onPlayerDied(player, hit: { why: string, by?: string, npc?: number, kind?: string, weapon?: string })
event#

A player reached 0 health and is down.

example.js
js
eg.ui.toast(null, eg.t('{name} is down!', { name: player }), 'warn');
if (hit.by) eg.scores.add(hit.by, 25);
What happens in gametoast

Fires at 0 HP so you can award elimination points, drop loot zones, or announce knockouts.

Mira is down!
onPlayerRespawn(player)
event#

A downed player is back on their feet.

example.js
js
eg.inventory.setLoadout(player, { pistol: 36, bat: 1 });
eg.ui.toast(player, 'Back in the fight!', 'good');
What happens in gametoast

Fires when the downed timer expires or `combat.respawn` runs, letting you re-equip weapons or warp them to base.

Back in the fight!
onRace(player, race: { ev: 'start' | 'gate' | 'finish' | 'void', track: string, name?: string, cls?: string, car?: string, racers?: number, n?: number, of?: number, ms?: number, splits?: number[], par?: number, lengthM?: number, mode?: string, place?: number, featured?: boolean, user?: boolean, course?: boolean, reason?: string })
event#

A race you offered moved on. "start": the lights began (racers: how many on them). "gate": gate n of "of" crossed at ms. "finish": every gate crossed in ms milliseconds, with the splits, the par for their car's class (cls), and their place among "of" racers when it was a heat. "void": it ended without a time; reason is teleport, correct, fly, onfoot, swap, fast, expired or cancelled.

example.js
js
if (race.ev === 'finish') {
  eg.fx.confetti(player);
  eg.ui.toast(null, eg.t('{name} finished in {s} s', { name: player, s: (race.ms / 1000).toFixed(2) }), 'good');
}
What happens in gamebanner

Streams race lifecycle events (`start`, `gate`, `finish`, `void`) with exact server split times, car class par, and heat placement.

FINISH · 1st of 40:42.18 · Beat Class B Par
onNpc(event: { ev: 'spawned' | 'died' | 'saw' | 'lost' | 'reached' | 'attack' | 'gone', id: number, player?: Player, kind?: string, damage?: number, spawner?: string, tag?: string, lat?: number, lon?: number, why?: string })
event#

Something happened to one of the game's characters. `player` is who it saw, attacked or was killed by; `died` says where (lat, lon); `gone` says why it was removed.

example.js
js
if (event.ev === 'died' && event.player) {
  eg.scores.add(event.player, 10);
  eg.ui.toast(event.player, '+10 pts', 'good');
}
What happens in gametoast

Reports character sightings, attacks, arrivals (`reached`), deaths (with attacker & coordinates), and despawns.

+10 pts

eg.world

Time, distance, bearings, real places, and instance weather/solar-hour atmosphere. Everything works wherever on Earth the game is played.

eg.world.now(): number
local#

The time now, in milliseconds since 1970 (the server clock).

example.js
js
const endAt = eg.world.now() + 90_000;
eg.ui.hud(player, [{ type: 'timer', until: endAt, text: 'left' }]);
What happens in gamehud

Uses the server clock (matching the client countdown) so every player's HUD clock counts down in sync.

Clock Sync
⏱1:30 left
eg.world.distance(a: point, b: point): number
local#

Metres between two points.

example.js
js
const goal = eg.world.offset(player, 150, 0);
const d = Math.round(eg.world.distance(player, goal));
eg.ui.toast(player, eg.t('{d} m away', { d }));
What happens in gameworld

Computes the exact straight-line distance in metres across the 1:1 Earth sphere between two points or players.

150 m Sphere distance Exact ground metres between player and goal beacon
eg.world.offset(from: point, eastM: number, southM: number): point
local#

The point that many metres east and south of another: place things relative to wherever the game is being played.

example.js
js
const camp = eg.world.offset(player, 40, -25); // 40 m east, 25 m north
eg.entities.add({ id: 'camp', kind: 'zone', at: camp, radius: 8, style: 'safehouse', label: 'Camp' });
What happens in gameworld

Spawns a glowing green safehouse ring 40 m east and 25 m north of the player without hardcoding coordinates.

40 m E · 25 m N Relative placement Safehouse ring placed relative to player anywhere on Earth
eg.world.hour(at: point): number
local#

Local solar hour (0 to 24) at a point, for "only at night" rules anywhere on Earth.

example.js
js
const hr = eg.world.hour(player);
if (hr >= 20 || hr < 6) eg.ui.toast(player, 'Night bonus active!', 'good');
What happens in gameworld

Reads the real local sun hour (0–24) at that spot on Earth so night rules trigger only after dusk in the player's town.

21:40 SOLAR Local Solar Check Matches real sunset & sunrise at the player longitude
eg.world.placesNear(at: point, opts?: { minM?: number, maxM?: number, kinds?: string[], max?: number, seed?: string }): Promise<Place[]>
async · Promise#

Real named places from the built map between minM and maxM metres of a point: [{ id, name, kind (depot | fuel | shop | office), lat, lon }], each on the road in front of it. The same seed gives the same sample. Three more kinds come only when you ask for them in `kinds`: "hospital", "police" (a police station) and "street" (a point on a named street).

example.js
js
const stops = await eg.world.placesNear(player, { minM: 150, maxM: 1200, kinds: ['shop', 'fuel'], max: 4 });
for (const s of stops) eg.entities.add({ id: 'p-' + s.id, kind: 'zone', at: s, label: s.name, style: 'pickup', trigger: {} });
What happens in gameworld

Queries real built-map businesses and streets around the player and turns them into named interactive rings on the road.

4 REAL PLACES Corner Store · Shell Fuel Map-sourced zones placed on roads right outside real buildings
eg.world.onRoad(at: point): Promise<boolean | null>
async · Promise#

Is this point on a road? null where the map is not built.

example.js
js
const spot = eg.world.randomPoint(player, { minM: 40, maxM: 120 });
if (await eg.world.onRoad(spot)) {
  eg.entities.add({ id: 'flare', kind: 'marker', at: spot, style: 'hot', label: 'Road Flare' });
}
What happens in gameworld

Verifies a candidate coordinate actually lands on paved road surface before spawning a roadblock, flare, or vehicle event.

ON ROAD Road surface verified Places flare cleanly on asphalt instead of inside a building
eg.world.bearing(from: point, to: point): number
local#

Compass bearing in degrees from one point toward another (0 north, 90 east, 180 south, 270 west).

example.js
js
const target = eg.world.offset(player, 120, -120);
const deg = Math.round(eg.world.bearing(player, target));
eg.ui.toast(player, eg.t('Head {deg} deg', { deg }));
What happens in gametoast

Returns the compass heading (0 north, 90 east) so scripts can give directional callouts or place objects ahead.

Head 45 deg (NE)
eg.world.pointAlong(from: point, bearingDeg: number, meters: number): point
local#

The point `meters` away from `from` along a compass bearing in degrees.

example.js
js
const ahead = eg.world.pointAlong(player, 90, 200); // 200 m due east
eg.ui.waypoint(player, ahead, { hint: 'Check the alley.' });
What happens in gameworld

Places a point 200 m along a compass angle and directs the player's GPS navigation line straight to it.

090 deg · 200 m Waypoint projected GPS line curves along real streets toward the point
eg.world.midpoint(a: point, b: point): point
local#

The point halfway between two points.

example.js
js
const [a, b] = eg.players.all();
if (a && b) eg.entities.add({ id: 'arena', kind: 'zone', at: eg.world.midpoint(a, b), radius: 25, style: 'hot', label: 'Meet' });
What happens in gameworld

Places a red capture ring directly halfway between two players so both have an equal sprint to reach it.

MIDPOINT Equidistant arena ring Hot red zone spawned halfway between two players
eg.world.inRadius(at: point, center: point, radiusM: number): boolean
local#

True when `at` is within `radiusM` metres of `center`.

example.js
js
const base = eg.state.base;
if (base && eg.world.inRadius(player, base, 30)) {
  eg.ui.toast(player, 'Safe inside base.', 'good');
}
What happens in gametoast

Checks quickly in memory whether a player or NPC stands inside a circular area before rewarding points or healing.

Safe inside base.
eg.world.randomPoint(center: point, opts?: { minM?: number, maxM?: number }): point
local#

A random point evenly distributed inside a circle or ring (`minM` to `maxM` metres, default 0 to 100) around `center`.

example.js
js
const drop = eg.world.randomPoint(player, { minM: 80, maxM: 220 });
eg.entities.add({ id: 'crate', kind: 'marker', at: drop, style: 'pickup', label: 'Supply Drop', radar: true });
What happens in gameworld

Drops a glowing amber supply beacon somewhere inside an 80–220 m ring around the player and marks it on the minimap.

80-220 m RING Supply Drop Beacon Amber marker beam visible in 3D sky & minimap
eg.world.setWeather(weather: WeatherPreset | null)
cmdprivate games#

Override the weather ("clear", "cloudy", "overcast", "rain", "storm", "snow", "fog") for everyone in the instance (null restores live local weather).

example.js
js
eg.world.setWeather('storm');
eg.ui.toast(null, 'A storm is rolling in!', 'warn');
What happens in gameworld

Transitions the 3D sky, clouds, rain/snow particles, wind sway on trees, and wet road grip across the whole instance.

STORM Sky, Rain & Road Grip Dark clouds, heavy rainfall, tree gusts and slick asphalt
eg.world.setTime(hour: number | null)
cmdprivate games#

Pin the local solar hour (0 to 24, for instance 22 for night or 6.5 for sunrise) for everyone in the instance (null restores real local time).

example.js
js
eg.world.setTime(22.5); // 10:30 PM night sky
eg.ui.toast(null, 'Lights out. Survive until dawn.');
What happens in gameworld

Pins the sun below the horizon for everyone in the match, illuminating stars, streetlights, headlights, and marker beams.

22:30 NIGHT Night Sky Override Stars appear, headlights and neon beacons light the street
eg.world.lightning(at?: point | null)
cmdprivate games#

Flash the sky and play thunder for players near a point, or everyone in the instance when omitted.

example.js
js
eg.world.setWeather('storm');
eg.world.lightning(player);
What happens in gameworld

Sends a bright sky lightning flash and rolling thunder boom to players near the bolt, heightening storm tension.

LIGHTNING Sky flash + thunder SFX Brief white sky flash followed by spatial thunderclap

eg.players

Who is in the game: queries, teams, ephemeral match data, movement freezes, and teleports. Player objects are snapshots; call players.get for a fresh one.

eg.players.all(): Player[]
local#

Everyone in the game now.

example.js
js
for (const p of eg.players.all()) {
  eg.ui.toast(p, eg.t('Match starts! {n} players ready.', { n: eg.players.count() }), 'good');
}
What happens in gametoast

Iterates every player currently in the match so you can greet, teleport, equip, or score all participants.

Match starts! 6 players ready.
eg.players.get(player): Player | null
local#

The latest snapshot of one player, or null when they are not in the game.

example.js
js
const fresh = eg.players.get(player);
if (fresh && fresh.speed > 20) eg.ui.toast(fresh, 'Top speed bonus!');
What happens in gamehud

Fetches the player's up-to-date snapshot (position, speed, health, team, vehicle) instead of holding onto an older event copy.

Speed Trap
Current speed24.5 m/s
eg.players.near(at: point, radiusM: number): Player[]
local#

Players within a radius of a point, nearest first.

example.js
js
const nearby = eg.players.near(player, 25);
eg.ui.toast(player, eg.t('{n} players within 25 m', { n: nearby.length }));
What happens in gameworld

Lists everyone standing or driving within 25 m sorted closest-first—ideal for aura heals, blast checks, or proximity tag.

25 m RADIUS Proximity Scan Returns nearest players first for area effects
eg.players.nearest(at: point, opts?: { exclude?: player | player[], team?: string, alive?: boolean, maxM?: number }): Player | null
local#

The closest player to a point matching optional filters (`exclude`, `team`, `alive`, `maxM`), or null when none match.

example.js
js
const prey = eg.players.nearest(player, { exclude: player, alive: true, maxM: 150 });
if (prey) eg.ui.waypoint(player, prey, { hint: 'Target spotted!' });
What happens in gameworld

Finds the single closest living opponent (excluding the hunter) and locks the player's GPS arrow onto them.

NEAREST TARGET GPS Locked on Rival Updates GPS arrow to closest living player within 150 m
eg.players.inTeam(team: string): Player[]
local#

Everyone currently assigned to a team.

example.js
js
const blues = eg.players.inTeam('blue');
for (const p of blues) eg.combat.heal(p, 25);
What happens in gamehud

Filters directly to members of one team so you can reward, heal, or teleport only that squad.

Team Medic
BLUE TEAM +25 HP
eg.players.random(opts?: { team?: string, alive?: boolean, exclude?: player | player[] }): Player | null
local#

One randomly chosen player matching optional filters, or null when none match.

example.js
js
const seeker = eg.players.random({ alive: true });
if (seeker) {
  eg.players.setData(seeker, 'it', true);
  eg.ui.banner(seeker, { title: 'YOU ARE IT!', tone: 'warn', seconds: 4 });
}
What happens in gamebanner

Picks a fair random living player at round start to become the tagger, VIP, or driver.

YOU ARE IT!Tag another player before time runs out
eg.players.count(): number
local#

How many players are in the game.

example.js
js
if (eg.players.count() < 2) {
  eg.ui.hint(null, 'Waiting for at least 2 players...');
}
What happens in gametoast

Checks live headcount to gate round starts, scale wave counts, or show a waiting hint when solo.

Waiting for at least 2 players...
eg.players.isBusy(player): boolean
local#

True when the player is marked busy with `players.setBusy` or in a race.

example.js
js
if (!eg.players.isBusy(player)) {
  eg.ui.toast(player, 'Visit any beacon to start a run!');
}
What happens in gamehud

Checks whether a player is mid-race or marked busy so menus and world prompts don't overlap an active run.

Status
BUSY ON RUN
eg.players.setData(player, key: string, value: any)
local#

Keep an ephemeral value on a player for this run (up to 50 keys per player; cleared when they leave).

example.js
js
const pts = (eg.players.getData(player, 'coins') || 0) + 1;
eg.players.setData(player, 'coins', pts);
eg.ui.hud(player, [{ type: 'counter', text: 'Coins', value: pts }]);
What happens in gamehud

Tracks per-player counters or flags (coins, streaks, role) for this match without manual Map boilerplate.

Treasure Run
Coins7
eg.players.getData(player, key?: string): any
local#

Read one ephemeral value set with `players.setData` (or all keys as an object when `key` is left out).

example.js
js
const role = eg.players.getData(player, 'role') || 'runner';
eg.ui.toast(player, eg.t('Your role: {role}', { role }));
What happens in gametoast

Reads back ephemeral match data stored on that player (automatically cleaned up when they leave).

Your role: runner
eg.players.skipped(player, sinceMs: number): 'teleport' | 'correct' | 'fly' | null
local#

Did this player skip the trip since a moment (teleported, was snapped back by the server, or flew)? null when the trip was honest. For games that reward getting somewhere.

example.js
js
const startAt = eg.world.now();
eg.players.setData(player, 'startAt', startAt);
// Later on arrival:
if (eg.players.skipped(player, eg.players.getData(player, 'startAt'))) {
  eg.ui.toast(player, 'Trip voided: fast travel detected.', 'warn');
}
What happens in gametoast

Catches teleports or flight shortcuts since a timestamp so delivery and courier games only score honest trips.

Trip voided: fast travel detected.
eg.players.setBusy(player, busy: boolean)
cmd#

Mark a player as in the middle of a run (a job, a round). The platform will not move a busy player to another game without telling you first.

example.js
js
eg.players.setBusy(player, true);
eg.ui.toast(player, 'Heist active!');
What happens in gamehud

Tells Earth Games the player is in an active job or round so they aren't silently switched into another game.

Active Job
LOCKED IN RUN
eg.players.startRun(player): Promise<boolean>
async · Promise#

Ask the platform whether this player may start a scored run now. False when a free player has used up their runs for the day; the platform has already told them. Call it before starting anything that ends with finishRun.

example.js
js
if (await eg.players.startRun(player)) {
  eg.players.setBusy(player, true);
  eg.ui.toast(player, 'Scored run started!', 'good');
}
What happens in gametoast

Checks daily free-play quota before starting a scored run; automatically prompts free players when daily runs are used.

Scored run started!
eg.players.finishRun(player)
cmd#

A run that began with startRun was completed. Counts as having played the game.

example.js
js
eg.players.setBusy(player, false);
eg.players.finishRun(player);
What happens in gameresult

Records a completed scored run on the player's account and unlocks game rating after completion.

Run CompletedRecorded on player history · Unlocks rating
eg.players.award(player, badge: { id: string, label: string }): Promise<boolean>
async · Promiseteam only#

Give a signed-in player a profile badge. Resolves true when it is new to them.

example.js
js
const won = await eg.players.award(player, { id: 'deliveries:first', label: 'First Delivery' });
if (won) eg.ui.toast(player, 'Badge unlocked: First Delivery!', 'good');
What happens in gameresult

Awards a permanent profile badge (official Earth Games team games only) and notifies the player when newly earned.

Badge Unlocked🏅 First Delivery added to profile
eg.players.teleport(player, to: point)
cmdprivate games#

Move a player to a point at once: the start of a round, a respawn point.

example.js
js
const spawn = eg.world.offset(player, 0, -80);
eg.players.teleport(player, spawn);
eg.fx.ring(spawn, { color: '#38bdf8', radius: 5 });
What happens in gameworld

Instantly relocates the player to a starting line, lobby, or checkpoint and snaps their camera smoothly.

TELEPORT Instant Relocation Player moved to start point with camera snap
eg.players.teleportAll(to: point, opts?: { spreadM?: number })
cmdprivate games#

Move everyone in the instance to a point, optionally spaced evenly around a ring of `spreadM` metres (0 to 100).

example.js
js
const hub = eg.state.hub || player;
eg.players.teleportAll(hub, { spreadM: 12 });
eg.ui.toast(null, 'Everyone gathered at the start line!', 'good');
What happens in gameworld

Warps every player in the match into a neat circle around a hub point so nobody spawns stacked inside each other.

GROUP WARP 12 m Ring Formation All players spaced evenly around the start point
eg.players.setFrozen(player | null, frozen: boolean)
cmdprivate games#

Freeze or unfreeze a player (null: everyone). Frozen players cannot walk or drive, while still able to look around and answer prompts or windows.

example.js
js
eg.players.setFrozen(null, true);
eg.ui.countdown(null, { seconds: 3, goText: 'GO!' });
eg.timers.after(3, () => eg.players.setFrozen(null, false));
What happens in gamecountdown

Holds players in place (and locks car brakes) during a 3-second countdown while still letting them look around or click UI.

3HOLD POSITION
eg.players.eject(player)
cmdprivate games#

Put a player out of the vehicle they are driving onto foot beside it.

example.js
js
if (player.mode === 'drive') {
  eg.players.eject(player);
  eg.ui.toast(player, 'Vehicles disabled in this zone!', 'warn');
}
What happens in gametoast

Dismounts a driving player safely onto the pavement beside their car when entering a foot-only arena.

Vehicles disabled in this zone!
eg.players.kick(player, reason?: string)
cmdprivate games#

Send a player out of this private instance back to the shared world with an optional message.

example.js
js
const ok = await eg.ui.confirm(player, { title: 'Leave match?', body: 'Return to Free Roam?' });
if (ok) eg.players.kick(player, 'Returned to Free Roam.');
What happens in gametoast

Sends a player out of the private instance back to the shared world and displays your optional reason toast.

Returned to Free Roam.
eg.players.pay(player, cash: number): Promise<number>
async · Promiseteam only#

Add to a player's cash in this game (a negative number takes some, down to nothing). Resolves to what they have now.

example.js
js
const bal = await eg.players.pay(player, 250);
eg.ui.toast(player, eg.t('Paid! Balance: {bal}', { bal }), 'good');
What happens in gameresult

Adds or subtracts game cash (official Earth Games team games only) and resolves to their updated wallet balance.

Wallet Updated+$250 · New balance $1,450
eg.players.wanted(at: point, radiusM: number): Promise<{ id: string, name: string, level: number, lat: number, lon: number }[]>
async · Promiseteam only#

Players within a radius who are wanted by the police in another Earth Games game right now, nearest first, with where they are. An id lasts while that player stays online.

example.js
js
const suspects = await eg.players.wanted(player, 2000);
for (const s of suspects) eg.ui.toast(player, eg.t('{name} wanted level {lv}', { name: s.name, lv: s.level }));
What happens in gameworld

Lists nearby suspects wanted in Lawless (official team games only) with live coordinates and heat level.

HEAT 4 Wanted Suspect Nearby Live patrol radar shows suspect location
eg.players.grantCar(player, car: string): Promise<boolean>
async · Promiseteam only#

Put a car from the roster in a signed-in player's garage for good (a prize). Resolves true when it is new to them.

example.js
js
const fresh = await eg.players.grantCar(player, 'rally');
if (fresh) eg.ui.toast(player, 'Unlocked a new garage car!', 'good');
What happens in gameresult

Permanently adds a roster vehicle into the player's garage (official Earth Games team games only).

Garage RewardUnlocked rally car in permanent garage

eg.teams

Sides in a game, with scores, shuffling, leader lookups, and team broadcasts.

eg.teams.define(teams: { id: string, name?: string, color?: 'red' | 'blue' | 'green' | 'yellow' | 'purple' | 'orange' }[])
cmd#

Say which teams the game has (up to 8). Scores of teams that stay are kept; a player on a team that is gone has none.

example.js
js
eg.teams.define([
  { id: 'red', name: 'Crimson', color: 'red' },
  { id: 'blue', name: 'Cobalt', color: 'blue' },
]);
What happens in gamehud

Registers up to 8 colored squads for the game so team score pills and friendly-fire protection work automatically.

Teams Ready
Crimson 0Cobalt 0
eg.teams.assign(player, team: string | null)
cmd#

Put a player on a team (null: on none). Their snapshot has `team` from the next event on. Teammates cannot hurt each other unless combat is enabled with friendlyFire.

example.js
js
eg.teams.assign(player, 'red');
eg.ui.toast(player, 'Joined Crimson team.', 'info');
What happens in gamehud

Moves a player onto a specific team; from the next event onward `player.team` reflects it and teammates are protected.

Squad Assigned
CRIMSON TEAM
eg.teams.auto()
cmd#

Put every player who has no team on the team with the fewest players.

example.js
js
eg.teams.auto();
eg.ui.hud(null, [{ type: 'teams' }]);
What happens in gamehud

Automatically balances every unassigned player onto whichever team currently has the fewest players.

Balanced Teams
Red 0Blue 0
eg.teams.addScore(team: string, points: number)
cmd#

Add to a team's score (a negative number takes away).

example.js
js
if (player.team) {
  eg.teams.addScore(player.team, 10);
  eg.ui.hud(null, [{ type: 'teams' }]);
}
What happens in gamehud

Increments (or deducts) points on a team's scoreboard and updates everyone's HUD team strip when resent.

Score +10
Red 10Blue 4
eg.teams.setScore(team: string, points: number)
cmd#

Set a team's score.

example.js
js
eg.teams.setScore('red', 0);
eg.teams.setScore('blue', 0);
What happens in gamehud

Directly overwrites a team's score, useful for setting starting lives or resetting points between stages.

Score Set
Red 0Blue 0
eg.teams.all(): Promise<Team[]>
async · Promise#

The teams now, with their scores and the ids of the players on each.

example.js
js
const teams = await eg.teams.all();
const lines = teams.map(t => t.name + ': ' + t.score);
eg.ui.card(null, { title: 'Scoreboard', lines });
What happens in gamecard

Reads all teams, their colors, live scores, and member lists to render end-of-round summaries or tiebreakers.

Scoreboard Crimson: 24Cobalt: 18
Close
eg.teams.get(team: string): Promise<Team | null>
async · Promise#

One team by id, with its color, score and player ids, or null.

example.js
js
const red = await eg.teams.get('red');
if (red) eg.ui.toast(player, eg.t('Red has {n} pts', { n: red.score }));
What happens in gametoast

Fetches one team's score and player list without needing to filter the full team list manually.

Red has 24 pts
eg.teams.leader(): Promise<(Team & { tied: boolean }) | null>
async · Promise#

The highest-scoring team right now (`tied` is true when two or more teams share the lead), or null when no teams are defined.

example.js
js
const top = await eg.teams.leader();
if (top && !top.tied) {
  eg.ui.banner(null, { title: eg.t('{name} wins!', { name: top.name }), tone: 'good' });
}
What happens in gamebanner

Identifies the leading team right now and flags `tied: true` when two squads share top score so you can trigger overtime.

Crimson wins!24 pts · No tie
eg.teams.resetScores()
cmd#

Set every defined team's score back to 0.

example.js
js
eg.teams.resetScores();
eg.ui.hud(null, [{ type: 'teams' }]);
What happens in gamehud

Zeroes every team's score at once while preserving team rosters and colors for the next round.

New Round
Red 0Blue 0
eg.teams.shuffle()
cmd#

Randomly rebalance every player currently in the game evenly across the defined teams.

example.js
js
eg.teams.shuffle();
eg.chat.announce('Teams have been shuffled for a fresh round!');
What happens in gamechat

Randomly redistributes all players evenly across your defined teams between rounds so matches stay fair.

MatchTeams have been shuffled for a fresh round!
eg.teams.broadcast(team: string, text: string, tone?: 'info' | 'good' | 'warn')
cmd#

Show a toast message only to players on one team.

example.js
js
eg.teams.broadcast('red', 'Regroup at the northern bridge!', 'warn');
What happens in gametoast

Sends a private toast banner exclusively to teammates on one squad without tipping off opposing teams.

[Red Team] Regroup at the northern bridge!

eg.vehicles

What players drive: emergency sirens, handling profiles, tire compounds, speed caps, and nitro boosts.

eg.vehicles.siren(player, on: boolean)
cmd#

Switch the emergency siren of the vehicle a player is driving on or off: traffic makes way for them, and players near them hear it.

example.js
js
if (player.mode === 'drive') {
  eg.vehicles.siren(player, true);
}
What happens in gameworld

Flashes emergency lights and plays a two-tone yelp audible within 300 m while ambient traffic pulls aside.

SIREN ON Lights & Two-Tone Yelp Nearby traffic clears the lane · 300 m audio relay
eg.vehicles.setHandling(profile: HandlingProfile)
cmdprivate games#

Set ground-vehicle handling for everyone in the instance: "arcade" (forgiving grip), "sport" (eager and lively), or "real" (factory road specs).

example.js
js
eg.vehicles.setHandling('sport');
eg.ui.toast(null, 'Sport handling enabled!', 'info');
What happens in gamehud

Switches every ground vehicle in the instance between forgiving "arcade", lively "sport", or realistic factory physics.

Vehicle Physics
HANDLING: SPORT
eg.vehicles.setTire(player | null, tire: TireCompound | null)
cmdprivate games#

Fit a tire compound ("slick", "allweather", "gravel", or null for default) on a player's vehicle or everyone's.

example.js
js
eg.vehicles.setTire(player, 'gravel');
eg.ui.toast(player, 'Rally gravel tires fitted!', 'good');
What happens in gametoast

Swaps tire grip profile ("slick", "allweather", "gravel") so cars bite harder on dirt, rain, or dry tarmac.

Rally gravel tires fitted!
eg.vehicles.setSpeedLimit(player | null, maxMps: number | null)
cmdprivate games#

Cap ground-vehicle speed in metres per second (for pit lanes or speed traps); null removes the cap.

example.js
js
eg.vehicles.setSpeedLimit(player, 15); // 15 m/s (~33 mph) pit lane cap
What happens in gamehud

Gently enforces a maximum ground speed for pit lanes, school zones, or handicap rules; pass null to uncap.

Pit Lane
SPEED CAP 15 m/s
eg.vehicles.boost(player, opts?: { strength?: number, seconds?: number })
cmdprivate games#

Give a player's ground vehicle a temporary speed and acceleration surge (`strength` 0.2 to 2, `seconds` 0.3 to 8).

example.js
js
eg.vehicles.boost(player, { strength: 1.4, seconds: 2.5 });
eg.audio.cue(player, 'ui.race_go');
What happens in gameworld

Surges the player's vehicle forward with extra acceleration and speed-widened FOV for a nitro pad or pickup effect.

NITRO +1.4x Speed Surge (2.5 s) Boosts forward thrust and widens chase camera FOV

eg.camera

What a player's camera and viewport do: shakes, field-of-view kicks, and smooth screen fades.

eg.camera.shake(player | null, opts?: { strength?: number, seconds?: number })
cmd#

Shake a player's camera for a moment (null: everyone): a blast, a landing, something heavy going past. Not shown to players who asked their device for less motion.

example.js
js
eg.camera.shake(player, { strength: 1.8, seconds: 0.6 });
What happens in gameworld

Rattles the player's camera for impacts or explosions (automatically skipped for reduced-motion preferences).

CAM SHAKE Impact Tremor (0.6 s) Shakes 3D camera; respects reduced-motion accessibility
eg.camera.fov(player | null, opts: { kick?: number, seconds?: number } | null)
cmd#

Widen or narrow a player's field of view by `kick` degrees (-15 to 15) for `seconds` (0.1 to 30); null resets to normal.

example.js
js
eg.camera.fov(player, { kick: 10, seconds: 3 });
What happens in gameworld

Smoothly widens (positive kick) or narrows (negative zoom) the 3D camera field of view for adrenaline or focus.

FOV +10 deg Dynamic Camera Zoom Widens perspective smoothly for 3 seconds then eases back
eg.camera.fade(player | null, opts: { color?: "black" | "white", opacity?: number, seconds?: number } | null)
cmd#

Fade a player's screen smoothly toward black or white (`opacity` 0 to 1, `seconds` 0.1 to 5); pass opacity 0 or null to fade back in.

example.js
js
eg.camera.fade(player, { color: 'black', opacity: 1, seconds: 0.6 });
eg.timers.after(0.7, () => {
  eg.players.teleport(player, eg.world.offset(player, 200, 0));
  eg.camera.fade(player, null);
});
What happens in gameworld

Fades the viewport smoothly to black or white and back for clean round transitions, round wins, or teleports.

SCREEN FADE 0.6 s Smooth Transition Fades viewport cleanly before teleporting or ending a round

eg.race

Timed races through gates, on the tracks the platform makes from real streets or on a course of your own. The platform draws the gates and lights and keeps the time.

eg.race.tracksNear(at: point, opts?: { maxM?: number, max?: number }): Promise<Track[]>
async · Promise#

Race tracks on real streets near a point, nearest first: [{ id, name, kind ("sprint" | "circuit"), laps, lengthM, start, par: { D, C, B, A, S, M } (a good time in ms for each class of car), featured?, user? }]. The platform makes them from the map, and players record their own.

example.js
js
const tracks = await eg.race.tracksNear(player, { maxM: 2500, max: 3 });
if (tracks[0]) await eg.race.offer(player, tracks[0].id);
What happens in gamemenu

Finds real street circuits and point-to-point sprints near the player with par times tuned for each vehicle class.

Nearby Street Tracks✕
Elm Street Circuit2.4 km · 2 laps · Par B 1:42
Race
eg.race.course(points: point[], opts?: { name?: string, laps?: number }): Promise<Track | null>
async · Promise#

A course of your own through the points you give, in order (100 m to 20 km): the platform puts the gates on it. End within 30 m of the start for a circuit. It lasts as long as the game runs (up to 20 at a time). null when it cannot be made; your log says why.

example.js
js
const p1 = eg.world.offset(player, 150, 0);
const p2 = eg.world.offset(player, 250, -150);
const course = await eg.race.course([player, p1, p2], { name: 'Dock Sprint' });
What happens in gameworld

Generates timed holographic 3D gates and a glowing racing line along custom checkpoints you supply.

CUSTOM TRACK Dock Sprint (3 Gates) Draws holographic start gantry, road line and finish gates
eg.race.offer(player, track: string, opts?: { mode?: string }): Promise<{ ok: boolean, why?: 'racing' | 'unknown' | 'far' }>
async · Promise#

Put a player on a track (by its id): a ring appears on its start line. When they stop in it in a car or on a bike, the start lights count down and the platform times them through every gate; players of your game who line up together start together. You hear the rest in onRace. The player counts as busy until the race ends.

example.js
js
const tracks = await eg.race.tracksNear(player);
if (tracks[0]) await eg.race.offer(player, tracks[0].id, { mode: 'heat' });
What happens in gamecountdown

Places a golden start-grid ring on the road; stopping inside triggers 5 red start lights, multiplayer heats, and split timing.

LIGHTS5-light race grid · Splits timed server-side
eg.race.cancel(player)
cmd#

Take a player out of the race they are lining up for or driving. You hear onRace with ev "void", reason "cancelled".

example.js
js
eg.race.cancel(player);
eg.ui.toast(player, 'Left the race grid.', 'info');
What happens in gametoast

Removes a player from their active race or start grid, clears the gates, and fires `onRace` with reason "cancelled".

Left the race grid.
eg.race.status(player): Promise<{ track: string, stage: 'grid' | 'count' | 'race', next: number, total: number } | null>
async · Promise#

The race a player is currently in (`stage`, `next` gate and `total` gates), or null when they are not racing.

example.js
js
const st = await eg.race.status(player);
if (st) eg.ui.toast(player, eg.t('Gate {n} of {of}', { n: st.next + 1, of: st.total }));
What happens in gamehud

Checks what stage of a race a player is in ("grid", "count", or "race") and how many gates remain.

Race Progress
Gate 4 / 10

eg.entities

Zones and markers on the map: places players go to, stand in, inspect, or press F at.

eg.entities.add(def: { id?: string, kind: 'zone' | 'marker', at: point, radius?: number, style?: string, label?: string, radar?: boolean, visibleTo?: player, trigger?: { dwellS?: number, maxSpeed?: number, modes?: string[] }, interact?: { verb: string, reach?: number, modes?: string[] } }): string
local#

Put a zone (a ring players enter) or a marker (a beacon) on the map and return its id. `visibleTo` makes it one player's own. A `trigger` makes it fire onZone; `interact` gives it an F prompt that fires onInteract.

example.js
js
eg.entities.add({
  id: 'vault', kind: 'zone', at: eg.world.offset(player, 35, 0),
  radius: 6, style: 'pickup', label: 'Vault', radar: true,
  interact: { verb: 'Open Vault', reach: 6 }
});
What happens in gameworld

Renders a 3D glowing ring or beacon pillar in the world (plus optional minimap dot and "F: Open Vault" prompt).

ZONE + F Vault (6 m) Amber 3D ring on ground · Minimap dot · "F: Open Vault"
eg.entities.update(id: string, patch: object)
cmd#

Change an entity (same fields as add).

example.js
js
eg.entities.update('vault', { style: 'dropoff', label: 'Vault Open!' });
What happens in gameworld

Updates an entity's position, radius, label, color style, or minimap flag live without recreating it.

UPDATED Vault Open! (green) Color and floating label change immediately for players
eg.entities.remove(id: string)
cmd#

Take an entity off the map.

example.js
js
eg.entities.remove('vault');
What happens in gameworld

Immediately removes the ring or beacon from the 3D world, minimap, and player proximity triggers.

REMOVED Entity cleared 3D ring, beacon and minimap pin disappear
eg.entities.get(id: string): Promise<Entity | null>
async · Promise#

Read one entity your script placed by id, or null when it is not on the map.

example.js
js
const flag = await eg.entities.get('flag-1');
if (flag) eg.ui.waypoint(player, flag.at, { hint: flag.label });
What happens in gameworld

Reads back the live coordinates, radius, style, and label of any script entity so you can point GPS or distance HUDs at it.

INSPECT flag-1 (zone) Reads { id, kind, at, radius, style, label, radar }
eg.entities.list(opts?: { kind?: 'zone' | 'marker', prefix?: string, visibleTo?: player }): Promise<Entity[]>
async · Promise#

List the entities your script currently has on the map, optionally filtered by `kind`, id `prefix` or `visibleTo`.

example.js
js
const drops = await eg.entities.list({ kind: 'zone', prefix: 'coin-' });
eg.ui.toast(player, eg.t('{n} coins left on map', { n: drops.length }));
What happens in gametoast

Lists active entities filtered by kind, id prefix, or owner—handy for counting remaining collectibles or displaying a map directory.

12 coins left on map
eg.entities.near(at: point, radiusM: number, opts?: { kind?: 'zone' | 'marker', prefix?: string }): Promise<Entity[]>
async · Promise#

Your script's entities within `radiusM` metres of a point, nearest first.

example.js
js
const close = await eg.entities.near(player, 100, { prefix: 'loot-' });
eg.ui.toast(player, eg.t('{n} loot stashes within 100 m', { n: close.length }));
What happens in gameworld

Finds your nearest placed zones or markers around a player sorted closest-first for radar sweeps or local alerts.

100 m SCAN 3 Nearby Stashes Sorted closest-first around the player
eg.entities.count(opts?: { kind?: 'zone' | 'marker', prefix?: string }): Promise<number>
async · Promise#

How many entities your script currently has on the map.

example.js
js
if (await eg.entities.count({ prefix: 'gem-' }) === 0) {
  eg.ui.banner(null, { title: 'All gems found!', tone: 'good' });
}
What happens in gamebanner

Counts matching active entities quickly so you can detect when the final objective or collectible is cleared.

All gems found!0 remaining on the map
eg.entities.clear(opts?: { prefix?: string, visibleTo?: player })
cmd#

Remove every entity your script placed, or only those matching an id `prefix` or `visibleTo`.

example.js
js
eg.entities.clear({ prefix: 'temp-' });
What happens in gameworld

Wipes all entities (or a matching prefix/player's private markers) cleanly between rounds without touching active race start grids.

CLEARED Removed temp-* markers Map stays tidy between rounds

eg.npcs

Characters the game puts in the world. The platform moves them; you choose their kind, batch spawns, and what they are doing.

eg.npcs.kinds(kinds: Kind[])
cmdprivate games#

Define the kinds of characters this game uses: [{ id, name?, model?, scale?, speed?, runSpeed?, health?, sight?, leash?, brain?, aggro?, attack?: { range, damage, cooldownS, windupS, ranged? } }].

example.js
js
eg.npcs.kinds([
  { id: 'guard', name: 'Guard', brain: 'guard', health: 120, sight: 35, attack: { range: 1.6, damage: 12 } }
]);
What happens in gameworld

Registers custom AI character archetypes (speed, model, health, vision radius, melee/ranged attack) used by spawn and spawners.

NPC KIND Guard · 120 HP 35 m sight · 12 dmg melee attack
eg.npcs.spawn(kind: string, opts: SpawnOpts): Promise<number | null>
async · Promiseprivate games#

Spawn one character. Resolves to its id, or null when the kind is unknown or the world is full.

example.js
js
const spot = eg.world.offset(player, 18, 0);
const id = await eg.npcs.spawn('guard', { lat: spot.lat, lon: spot.lon, tag: 'boss' });
What happens in gameworld

Drops a live 3D AI character into the street that steers around buildings and reacts to nearby players.

SPAWNED #42 Guard on street Animated 3D character navigates around buildings
eg.npcs.spawnMany(kind: string, list: SpawnOpts[]): Promise<(number | null)[]>
async · Promiseprivate games#

Spawn up to 50 characters of one kind in a single call, returning their ids (or null for any that did not fit).

example.js
js
const spots = [1, 2, 3, 4].map(i => ({
  ...eg.world.randomPoint(player, { minM: 25, maxM: 50 }),
  tag: 'squad'
}));
const ids = await eg.npcs.spawnMany('guard', spots);
What happens in gameworld

Spawns an entire ambush squad or horde pack in a single call instead of awaiting dozens of separate spawns.

SQUAD x4 Batch Spawned 4 characters appear at once around 25-50 m
eg.npcs.despawn(id: number)
cmdprivate games#

Take a character out of the world at once.

example.js
js
const near = await eg.npcs.near(player, 15, { max: 1 });
if (near[0]) eg.npcs.despawn(near[0]);
What happens in gameworld

Removes one specific character from the world right away without leaving a body or death event.

DESPAWN Character removed Immediately cleared from player views
eg.npcs.despawnTag(tag: string): Promise<number>
async · Promiseprivate games#

Take every character with a matching `tag` out of the world at once. Resolves to how many were removed.

example.js
js
const removed = await eg.npcs.despawnTag('boss');
eg.ui.toast(null, eg.t('Cleared {n} guards.', { n: removed }));
What happens in gametoast

Despawns every character sharing a tag (like "wave-1" or "escort") in one shot and reports how many left.

Cleared 8 guards.
eg.npcs.clear()
cmdprivate games#

Remove every character.

example.js
js
eg.npcs.clear();
What happens in gameworld

Removes every active NPC in the match at once—helpful when resetting an arena or ending a horde phase.

ALL CLEARED 0 NPCs active Every character cleared from the instance
eg.npcs.setBrain(id: number, brain: 'idle' | 'wander' | 'chase' | 'flee' | 'guard' | 'patrol' | 'goto', opts?: { target?: player | point, route?: point[], home?: point, run?: boolean })
cmdprivate games#

Change what a character is doing.

example.js
js
const [id] = await eg.npcs.near(player, 40, { max: 1 });
if (id) eg.npcs.setBrain(id, 'chase', { target: player, run: true });
What happens in gameworld

Switches an NPC's live AI behavior (idle, wander, chase, flee, guard, patrol, goto), immediately changing where it runs.

AI: CHASE Sprinting at player Switches character to run directly toward target
eg.npcs.setBrainAll(filter: { kind?: string, tag?: string, spawner?: string }, brain: Brain, opts?: { target?: player | point, route?: point[], home?: point, run?: boolean }): Promise<number>
async · Promiseprivate games#

Change what every living character matching `kind`, `tag` or `spawner` is doing. Resolves to how many were updated.

example.js
js
await eg.npcs.setBrainAll({ tag: 'squad' }, 'flee', { target: player, run: true });
eg.ui.toast(null, 'The squad is retreating!', 'good');
What happens in gametoast

Orders an entire tag, kind, or spawner group to flee, charge, or patrol together when a boss falls or an alarm sounds.

The squad is retreating!
eg.npcs.damage(id: number, amount: number, by?: player): Promise<{ hp: number, died: boolean } | null>
async · Promiseprivate games#

Hurt a character.

example.js
js
for (const id of await eg.npcs.near(player, 8)) {
  await eg.npcs.damage(id, 50, player);
}
What happens in gameworld

Applies direct script damage to an NPC (credited to `by`)—killing it triggers `onNpc` "died" and leaves a body briefly.

-50 HP Character Damaged Drops NPC health; kills trigger onNpc "died"
eg.npcs.heal(id: number, amount: number)
cmdprivate games#

Heal a character.

example.js
js
for (const id of await eg.npcs.near(player, 20)) {
  eg.npcs.heal(id, 30);
}
What happens in gameworld

Restores health to a living NPC up to its kind's max HP—great for boss phases or healer enemies.

+30 HP Character Healed Boosts living NPC health up to max
eg.npcs.info(id: number): Promise<Npc | null>
async · Promiseprivate games#

One character: { id, kind, lat, lon, heading, hp, alive, brain, target, spawner, tag }.

example.js
js
const [id] = await eg.npcs.near(player, 50, { max: 1 });
const npc = id && await eg.npcs.info(id);
if (npc) eg.ui.waypoint(player, npc);
What happens in gameworld

Inspects a character's live coordinates, HP, brain, tag, and current target player.

NPC #12 guard · 85 HP · chase Live lat/lon lets GPS track moving bosses
eg.npcs.near(at: point, radiusM: number, opts?: { kind?: string, tag?: string, max?: number }): Promise<number[]>
async · Promiseprivate games#

Ids of living characters within a radius, nearest first.

example.js
js
const threats = await eg.npcs.near(player, 25, { kind: 'guard' });
eg.ui.hud(player, [{ type: 'counter', text: 'Nearby guards', value: threats.length }]);
What happens in gamehud

Finds living NPC ids inside a radius sorted nearest-first for proximity radars, traps, or shockwaves.

Threat Radar
Nearby guards3
eg.npcs.count(opts?: { kind?: string, spawner?: string }): Promise<number>
async · Promiseprivate games#

How many characters are alive.

example.js
js
const alive = await eg.npcs.count({ spawner: 'horde' });
eg.ui.hud(null, [{ type: 'counter', text: 'Enemies left', value: alive }]);
What happens in gamehud

Counts living characters (total, by kind, or by spawner) to drive wave progress bars and round-clear checks.

Wave 2
Enemies left14

eg.spawners

Rules that keep characters around the players, or around a spot, without you placing each one.

eg.spawners.add(def: { id: string, kind: string, at?: point, radius?: number, count?: number, capNear?: number, capTotal?: number, perSecond?: number, respawnS?: number, hours?: [number, number], brain?: string, tag?: string, where?: { roadClass?: string[], minFromPlayersM?: number, maxFromPlayersM?: number } })
cmdprivate games#

Add or replace a spawner. With `at` it keeps `count` characters alive around that spot. Without, it keeps characters around the players wherever they go, appearing on ground that matches `where`, never closer than minFromPlayersM.

example.js
js
eg.spawners.add({
  id: 'pack', kind: 'guard', capNear: 6, capTotal: 30, perSecond: 1,
  where: { minFromPlayersM: 45, maxFromPlayersM: 100 }
});
What happens in gameworld

Continuously maintains NPCs around moving players (or around a fixed spot) just out of sight on valid ground.

SPAWNER ON pack · 1/s · 45-100 m Populates streets dynamically as players travel
eg.spawners.remove(id: string, opts?: { clear?: boolean })
cmdprivate games#

Remove a spawner; `clear` also removes the characters it made.

example.js
js
eg.spawners.remove('pack', { clear: true });
What happens in gameworld

Deletes a spawner rule and optionally despawns all characters it produced.

REMOVED Spawner stopped Existing spawned pack cleared with clear: true
eg.spawners.enable(id: string, on: boolean)
cmdprivate games#

Switch a spawner on or off.

example.js
js
eg.spawners.enable('pack', false);
eg.ui.toast(null, 'Intermission: catch your breath!', 'good');
What happens in gametoast

Pauses or resumes spawning without deleting the rule—ideal for wave breaks or day/night cycles.

Intermission: catch your breath!
eg.spawners.setDensity(id: string, k: number)
cmdprivate games#

Scale a spawner (0 none, 1 as written, up to 4).

example.js
js
eg.spawners.setDensity('pack', 2.5); // 250% cap density
What happens in gameworld

Scales a spawner's active population up (up to 4x) or down as difficulty escalates across waves.

DENSITY 2.5x Escalated Spawner Raises near and total NPC caps automatically
eg.spawners.burst(id: string, n: number)
cmdprivate games#

Spawn up to n right now, ignoring the rate.

example.js
js
eg.spawners.burst('pack', 10);
eg.ui.banner(null, { title: 'AMBUSH!', tone: 'bad', seconds: 3 });
What happens in gamebanner

Instantly releases a burst of up to N characters around players, ignoring normal per-second trickle rate.

AMBUSH!10 enemies spawned around players
eg.spawners.clear(id: string)
cmdprivate games#

Remove the characters a spawner made.

example.js
js
eg.spawners.clear('pack');
What happens in gameworld

Removes every active character created by one spawner while keeping the spawner itself ready for the next wave.

CLEARED Pack despawned Spawner rule remains intact for next wave
eg.spawners.list(): Promise<{ id: string, kind: string, enabled: boolean, alive: number }[]>
async · Promiseprivate games#

All active spawners with whether each is enabled and how many characters from it are alive.

example.js
js
const list = await eg.spawners.list();
const rows = list.map(s => s.id + ': ' + s.alive + ' alive');
eg.ui.card(player, { title: 'Spawners', lines: rows });
What happens in gamecard

Returns each spawner's id, character kind, enabled state, and live headcount for admin/debug panels or wave monitors.

Spawners pack: 12 alivebosses: 1 alive

eg.combat

Health, armor, shields, damage, death and respawning. Switch it on and players can fight your characters (and each other, if you allow it).

eg.combat.enable(opts?: { health?: number, respawnS?: number, pvp?: boolean, npcDamage?: boolean, safeS?: number, friendlyFire?: boolean, loadout?: Loadout })
cmdprivate games#

Switch combat on. Every player gets health (100 unless you say), a health and weapon bar, and the starting loadout; their shots and swings hurt your characters; your characters' attacks hurt them (npcDamage: false to decide that yourself in onNpc). A player at 0 health is down for respawnS seconds (5; 0 means until you call combat.respawn), then back with full health and safeS seconds (3) of protection. Players only hurt each other with pvp: true.

example.js
js
eg.combat.enable({ health: 100, respawnS: 6, pvp: true, loadout: { pistol: 36, bat: 1 } });
What happens in gamehud

Activates server-validated weapons, health/armor bars, crosshair aiming, hit feedback, and automatic respawning.

Combat Active
HP 100 · Pistol 36
eg.combat.disable()
cmdprivate games#

Switch combat off: weapons are put away and nobody can be hurt by shots. Health and inventories are kept.

example.js
js
eg.combat.disable();
eg.ui.toast(null, 'Ceasefire! Weapons holstered.');
What happens in gametoast

Holsters everyone's weapons and disables gunfire damage while preserving current health and inventory items.

Ceasefire! Weapons holstered.
eg.combat.setPvp(on: boolean)
cmdprivate games#

Let players hurt each other, or stop them.

example.js
js
eg.combat.setPvp(true);
eg.ui.banner(null, { title: 'PvP Enabled', tone: 'warn', seconds: 3 });
What happens in gamebanner

Toggles friendly/rival player-vs-player damage live mid-match (safe lobby -> PvP arena).

PvP EnabledWatch your back!
eg.combat.setHealth(player, hp: number, max?: number)
cmdprivate games#

Set a player's health (and, optionally, their maximum). 0 kills them.

example.js
js
eg.combat.setHealth(player, 200, 200); // juggernaut boss HP
What happens in gamehud

Sets exact current and maximum HP on the player's health bar—great for juggernaut bosses or sudden-death 1 HP modes.

Juggernaut
HP 200 / 200
eg.combat.setArmor(player, armor: number)
cmdprivate games#

Set a player's armor, 0 to 100. Armor soaks 60 % of each hit until it is used up.

example.js
js
eg.combat.setArmor(player, 100);
eg.ui.toast(player, 'Heavy armor equipped!', 'good');
What happens in gamehud

Fills the player's armor meter (0–100); each incoming hit has 60% soaked by armor until depleted.

Armor
ARMOR 100%
eg.combat.setSafe(player, seconds: number)
cmdprivate games#

Give a player `seconds` (0 to 60) of spawn protection during which attacks do not hurt them.

example.js
js
eg.combat.setSafe(player, 8);
eg.ui.toast(player, '8 seconds of spawn shield!', 'good');
What happens in gamehud

Grants temporary spawn-protection invulnerability so players cannot be spawn-camped right after teleporting.

Protected
SHIELD 8s
eg.combat.damage(player, amount: number, opts?: { by?: player, why?: string }): Promise<{ hp: number, died: boolean } | null>
async · Promiseprivate games#

Hurt a player (a trap, a fall, a rule of your own). null when it did nothing: they are down already, or just respawned.

example.js
js
const res = await eg.combat.damage(player, 25, { why: 'lava' });
if (res && res.died) eg.ui.toast(player, 'Burned by hazard!', 'warn');
What happens in gameworld

Applies environmental or script damage (respecting armor and safe shields), flashes red, and triggers death at 0 HP.

-25 HP Hazard Damage Red screen flash + server HP update
eg.combat.heal(player, amount: number)
cmdprivate games#

Give health back, up to their maximum. Call it from a timer for health that comes back by itself.

example.js
js
eg.combat.heal(player, 40);
eg.fx.flash(player, { color: 'green', seconds: 0.3 });
What happens in gameworld

Restores health up to the player's maximum and updates their combat bar immediately.

+40 HP Health Restored Green edge flash + health bar fills smoothly
eg.combat.healAll(amount?: number)
cmdprivate games#

Heal every living player in the game (by `amount`, or back to full health when left out).

example.js
js
eg.combat.healAll();
eg.ui.toast(null, 'Wave cleared — full heal!', 'good');
What happens in gametoast

Tops up every living player's health (by an amount or to full max HP) at once between waves.

Wave cleared — full heal!
eg.combat.kill(player, why?: string)
cmdprivate games#

Put a player down at once.

example.js
js
eg.combat.kill(player, 'out_of_bounds');
What happens in gameworld

Immediately knocks a player down (bypassing armor/shields) and fires `onPlayerDied` with your reason.

DOWNED Out of Bounds Knocks player down immediately and starts respawn timer
eg.combat.respawn(player)
cmdprivate games#

Put a downed player back on their feet now, with full health.

example.js
js
eg.combat.respawn(player);
eg.players.teleport(player, eg.world.offset(player, 20, 0));
What happens in gametoast

Revives a downed player on their feet right away with full health and brief spawn protection.

Back on your feet!
eg.combat.reviveAll()
cmdprivate games#

Put every downed player in the game back on their feet now with full health.

example.js
js
eg.combat.reviveAll();
eg.ui.banner(null, { title: 'Squad Revived!', tone: 'good', seconds: 3 });
What happens in gamebanner

Revives every downed teammate across the match at once when a team captures a checkpoint or clears a wave.

Squad Revived!Everyone is back in action

eg.inventory

What each player carries: weapons, rounds, and any items of your own.

eg.inventory.give(player, item: string, count?: number)
cmdprivate games#

Give a player a weapon ("bat", "pistol", "smg", "shotgun"; a gun's count is its rounds) or any item of your own ("key", "medkit": lowercase ids the platform just counts for you).

example.js
js
eg.inventory.give(player, 'smg', 90);
eg.inventory.give(player, 'medkit', 2);
What happens in gamehud

Adds weapons and ammo onto the player's weapon wheel/bar or increments custom items tracked in their inventory.

Picked Up
+SMG (90) · +2 MEDKIT
eg.inventory.take(player, item: string, count?: number)
cmdprivate games#

Take some of an item away, or all of it when count is left out.

example.js
js
eg.inventory.take(player, 'medkit', 1);
eg.combat.heal(player, 50);
What happens in gametoast

Consumes an item or weapon rounds when used in a shop, craft recipe, or medkit action.

Used 1 medkit (+50 HP)
eg.inventory.setLoadout(player, loadout: Loadout)
cmdprivate games#

Replace everything a player carries: { pistol: 48, bat: 1, medkit: 2 }. Everyone always has fists.

example.js
js
eg.inventory.setLoadout(player, { shotgun: 24, pistol: 36, bat: 1, key: 1 });
What happens in gamehud

Replaces everything the player carries with a clean class kit; fists remain available at all times.

Breacher Kit
Shotgun 24 · Pistol 36 · Bat · Key
eg.inventory.equip(player, weapon: string)
cmdprivate games#

Put a weapon they carry in their hands.

example.js
js
eg.inventory.give(player, 'shotgun', 16);
eg.inventory.equip(player, 'shotgun');
What happens in gamehud

Puts the chosen weapon directly into the player's hands so they don't have to cycle the weapon wheel.

Equipped
SHOTGUN READY
eg.inventory.get(player): Promise<{ [item: string]: number }>
async · Promiseprivate games#

What a player carries now.

example.js
js
const bag = await eg.inventory.get(player);
eg.ui.toast(player, eg.t('Medkits: {n}', { n: bag.medkit || 0 }));
What happens in gametoast

Reads the full dictionary of weapons and custom items currently carried by a player.

Medkits: 2
eg.inventory.has(player, item: string, count?: number): Promise<boolean>
async · Promiseprivate games#

True when the player carries at least `count` (1 by default) of an item or weapon.

example.js
js
if (await eg.inventory.has(player, 'key', 1)) {
  eg.inventory.take(player, 'key', 1);
  eg.ui.toast(player, 'Unlocked!', 'good');
} else {
  eg.ui.toast(player, 'Need a key first.', 'warn');
}
What happens in gametoast

Checks in one call whether a player holds enough of an item to open a door, buy an upgrade, or extract.

Unlocked!
eg.inventory.clear(player)
cmdprivate games#

Remove everything from a player's inventory, leaving only fists.

example.js
js
eg.inventory.clear(player);
eg.ui.toast(player, 'Disarmed! Fists only.', 'warn');
What happens in gametoast

Strips every weapon and custom item from the player, returning them to bare fists.

Disarmed! Fists only.

eg.fx

Effects in the world (sparks, smoke, fire, confetti, rings, explosions, screen flashes), seen by everyone near.

eg.fx.blood(at: point | player, opts?: { size?: number })
cmdprivate games#

A splash of blood. Shown only when your manifest says the game has blood ("content": { "blood": true }), and only to signed-in players who turned blood on in their settings. Hits in combat do this for you.

example.js
js
eg.fx.blood(player, { size: 1.3 });
What happens in gameworld

Draws a blood splash in 3D only when manifest `content.blood` is true AND the viewer opted into blood in Settings.

BLOOD FX Age-Gated Hit Splash Visible only when manifest & player settings permit
eg.fx.impact(at: point | player, opts?: { size?: number })
cmdprivate games#

A puff of dust, as when something hits the ground or a wall.

example.js
js
eg.fx.impact(eg.world.offset(player, 4, 0), { size: 1.5 });
What happens in gameworld

Kicks up a quick puff of 3D dust where something lands or strikes a wall.

IMPACT 3D Dust Puff Short rising dust sprite visible to nearby players
eg.fx.sparks(at: point | player, opts?: { size?: number })
cmdprivate games#

A burst of sparks.

example.js
js
eg.fx.sparks(player, { size: 1.4 });
What happens in gameworld

Bursts bright golden additive sparks at a vehicle collision, lockpick, or trap.

SPARKS Additive Spark Burst Bright golden sparks scatter outward
eg.fx.smoke(at: point | player, opts?: { size?: number, seconds?: number })
cmdprivate games#

Smoke rising from a point for a few seconds.

example.js
js
eg.fx.smoke(eg.world.offset(player, 10, 0), { size: 1.8, seconds: 5 });
What happens in gameworld

Sends billowing gray smoke plumes rising into the air for several seconds to mark flares or wrecks.

SMOKE 5s Rising Smoke Plume Soft smoke puffs drift upward for 5 seconds
eg.fx.fire(at: point | player, opts?: { size?: number, seconds?: number })
cmdprivate games#

Flickering flames rising at a point for `seconds` (2 by default, up to 12).

example.js
js
eg.fx.fire(eg.world.offset(player, 8, 0), { size: 1.6, seconds: 6 });
What happens in gameworld

Spawns flickering additive flames rising from a hazard zone, wreck, or campfire for up to 12 seconds.

FIRE 6s Flickering 3D Flames Warm glowing flame particles rise from the spot
eg.fx.confetti(at: point | player, opts?: { size?: number })
cmdprivate games#

A celebratory burst of colorful confetti around a point or player.

example.js
js
eg.fx.confetti(player, { size: 1.4 });
eg.audio.cue(player, 'ui.race_finish');
What happens in gameworld

Showers colorful fluttering confetti around the winner in 3D space—awesome for podiums and milestone unlocks.

CONFETTI Celebration Burst Multicolored confetti particles flutter in 3D around player
eg.fx.ring(at: point | player, opts?: { color?: string, radius?: number, seconds?: number })
cmdprivate games#

An expanding shockwave or pulse ring on the ground.

example.js
js
eg.fx.ring(player, { color: '#38bdf8', radius: 12, seconds: 1.1 });
What happens in gameworld

Expands a crisp glowing pulse ring across the ground for radar pings, shockwaves, or zone captures.

PULSE RING 12 m Ground Shockwave Glowing ring expands outward and fades smoothly
eg.fx.explosion(at: point | player, opts?: { size?: number, damage?: number, radius?: number, by?: player })
cmdprivate games#

A blast everyone near sees and hears. With `damage` it hurts players and characters within `radius` metres (8), less the farther they are; `by` is the player credited.

example.js
js
eg.fx.explosion(eg.world.offset(player, 12, 0), { size: 1.5, damage: 75, radius: 10, by: player });
What happens in gameworld

Detonates a flash, fireball, and smoke cloud while dealing distance-scaled blast damage to players and NPCs.

BLAST 10 m Explosion + 75 Max Dmg Flash, fire, smoke & falloff damage in 10 m radius
eg.fx.flash(player | null, opts?: { color?: "red" | "white" | "green", seconds?: number })
cmdprivate games#

Flash the edges of a player's screen (null: everyone).

example.js
js
eg.fx.flash(player, { color: 'red', seconds: 0.4 });
What happens in gameworld

Flashes a red, white, or green vignette around the edges of the screen for hits, flashbangs, or heals.

VIGNETTE Red Edge Flash (0.4 s) Screen borders glow and fade cleanly

eg.ui

What a player sees: toasts, HUD cards, result cards, menus, rich multi-block windows, awaitable modal prompts & forms, banners, countdowns, hints, and GPS waypoints.

eg.ui.toast(player | null, text: string, tone?: 'info' | 'good' | 'warn')
cmd#

A short message. null sends it to everyone in the game.

example.js
js
eg.ui.toast(player, eg.t('Picked up the package!'), 'good');
What happens in gametoast

Slides a sleek pill notification under the top compass (`"info"`, `"good"` emerald, or `"warn"` amber) that auto-fades.

Picked up the package!
eg.ui.hud(player | null, parts: HudPart[] | null)
cmd#

Set a player's HUD card for this game (null clears it). See HUD_PARTS for the pieces.

example.js
js
eg.ui.hud(player, [
  { type: 'title', text: 'Escort' },
  { type: 'badge', text: 'LIVE', tone: 'good' },
  { type: 'bar', value: 75, max: 100, text: 'Convoy 75%' }
]);
What happens in gamehud

Replaces the game's top-center HUD card with live distances, clocks, progress bars, counters, badges, and buttons.

Escort
LIVE
Convoy 75%
eg.ui.card(player, card: { title: string, lines?: string[], buttons?: Button[], seconds?: number } | null)
cmd#

A result card (shown in place of the HUD until closed or `seconds` pass).

example.js
js
eg.ui.card(player, {
  title: 'Delivery Complete!',
  lines: ['Reward: +250 pts', 'Time: {time:84}'],
  buttons: [{ id: 'again', label: 'Play again' }, { id: 'close', label: 'Close', action: 'close' }],
  seconds: 15
});
What happens in gamecard

Temporarily displays a bold result card over the HUD with summary lines and action buttons until clicked or `seconds` pass.

Delivery Complete! Reward: +250 ptsTime: 1:24
Play againClose
eg.ui.menu(player, menu: { id: string, title: string, tabs?: { id: string, label: string }[], tab?: string, text?: string, items?: { id: string, title: string, detail?: string, button?: string, disabled?: boolean }[], rows?: string[], note?: string } | null)
cmd#

Open (or replace, or with null close) a panel with a list of choices. A choice fires onUi with { from: "menu", id, item }; a tab fires { from: "menu", id, tab }.

example.js
js
eg.ui.menu(player, {
  id: 'shop', title: 'Loadout Shop',
  tabs: [{ id: 'weapons', label: 'Weapons' }, { id: 'gear', label: 'Gear' }],
  tab: 'weapons',
  items: [{ id: 'smg', title: 'SMG', detail: '90 rounds · $150', button: 'Buy' }],
  note: 'Press J to toggle'
});
What happens in gamemenu

Opens a clean docked left-side list menu with tabs, live "… away" distances on geo items, and action buttons.

Loadout Shop✕
WeaponsGear
SMG90 rounds · $150
Buy
Press J to toggle
eg.ui.window(player | null, win: WindowDef | null)
cmd#

Open or update a structured window (up to 3 per player; null closes all). Supports centered modals or docked left/right panels with tabs, stats, bars, tables, callouts, badges, lists and buttons. Interactions fire onUi with from "window".

example.js
js
eg.ui.window(player, {
  id: 'briefing', title: 'Heist Briefing', subtitle: 'Downtown Bank',
  position: 'center', width: 'md', backdrop: true,
  blocks: [
    { type: 'stats', items: [{ label: 'Crew', value: '3/4' }, { label: 'Payout', value: '$5,000', tone: 'good' }] },
    { type: 'callout', tone: 'warn', title: 'Silent Entry', text: 'Stay off cameras until the vault opens.' },
    { type: 'bar', value: 2, max: 3, text: 'Prep Tasks 2 / 3' }
  ],
  buttons: [{ id: 'ready', label: 'Ready Up', style: 'primary' }, { id: 'close', label: 'Later', action: 'close', style: 'ghost' }]
});
What happens in gamewindow

Opens a rich structured window (centered modal or docked left/right panel) with stat grids, tables, callouts, lists, badges, tabs, and buttons.

Heist BriefingDowntown Bank
✕
Crew3/4
Payout$5,000
Silent EntryStay off cameras until the vault opens.
Ready UpLater
eg.ui.closeWindow(player | null, id?: string)
cmd#

Close one open window by id, or all open windows when `id` is omitted.

example.js
js
eg.ui.closeWindow(player, 'briefing');
What happens in gameresult

Closes one specific window by id (or all open windows for that player when id is omitted) without disturbing their HUD.

Window ClosedCloses "briefing" while HUD & other windows stay open
eg.ui.confirm(player, opts: ConfirmOpts): Promise<boolean>
async · Promise#

Open a Yes/No modal dialog for one player and await their answer (`true` when confirmed, `false` when cancelled, closed or timed out).

example.js
js
const sure = await eg.ui.confirm(player, {
  title: 'Start Sudden Death?',
  body: 'Respawns will be disabled for everyone.',
  ok: 'Start Now', cancel: 'Cancel', danger: true
});
if (sure) eg.ui.banner(null, { title: 'SUDDEN DEATH', tone: 'bad' });
What happens in gameprompt

Pops up a focus-trapped Yes/No confirmation modal, pauses driving keys cleanly, and resolves directly to `true` or `false` in your script.

CONFIRM Start Sudden Death?

Respawns will be disabled for everyone.

CancelStart Now
eg.ui.prompt(player, opts: PromptOpts): Promise<string | null>
async · Promise#

Open a text-input modal dialog for one player and await what they type (up to 240 characters), or `null` when cancelled.

example.js
js
const name = await eg.ui.prompt(player, {
  title: 'Name Your Squad',
  label: 'Team callsign',
  placeholder: 'e.g. Nighthawks',
  maxLength: 24
});
if (name) eg.ui.toast(player, eg.t('Callsign set: {name}', { name }), 'good');
What happens in gameprompt

Opens a focus-trapped text input dialog, releases pointer lock so the player can type, and awaits their sanitized string (or null on Cancel).

INPUT Name Your Squad
Team callsignNighthawks
CancelOK
eg.ui.choose(player, opts: ChooseOpts): Promise<string | null>
async · Promise#

Open a choice/dialogue picker modal for one player and await the chosen option's `id`, or `null` when cancelled.

example.js
js
const pick = await eg.ui.choose(player, {
  title: 'Choose Starting Class',
  body: 'Pick how you want to play this round.',
  options: [
    { id: 'medic', label: 'Field Medic', detail: '2x Medkits + Pistol' },
    { id: 'scout', label: 'Scout', detail: 'SMG + Fast Sprint' }
  ]
});
if (pick === 'medic') eg.inventory.give(player, 'medkit', 2);
What happens in gameprompt

Shows an interactive choice/dialogue picker modal and awaits whichever option id the player clicks (or null if dismissed).

CHOOSE Choose Starting Class
Field Medic2x Medkits + Pistol
ScoutSMG + Fast Sprint
Cancel
eg.ui.form(player, opts: FormOpts): Promise<{ [key: string]: string | number | boolean } | null>
async · Promise#

Open a multi-field modal form (`text`, `number`, `select`, `checkbox`, `slider`, up to 8 fields) and await `{ [name]: value }`, or `null` when cancelled.

example.js
js
const cfg = await eg.ui.form(player, {
  title: 'Match Settings',
  fields: [
    { name: 'rounds', label: 'Rounds', type: 'slider', min: 1, max: 10, value: 3 },
    { name: 'weather', label: 'Weather', type: 'select', options: [{ value: 'clear', label: 'Clear' }, { value: 'storm', label: 'Storm' }], value: 'clear' },
    { name: 'pvp', label: 'Allow PvP', type: 'checkbox', value: true }
  ],
  ok: 'Apply'
});
if (cfg) eg.world.setWeather(cfg.weather);
What happens in gameprompt

Renders a full multi-field settings or creator modal (text, number, select, checkbox, slider) and awaits typed, validated values.

FORM Match Settings
RoundsSlider: 3 / 10
WeatherSelect: Clear
Allow PvPChecked
CancelApply
eg.ui.banner(player | null, banner: BannerDef | null)
cmd#

Show a bold announcement banner across the upper center of the screen (null clears it).

example.js
js
eg.ui.banner(null, {
  title: 'WAVE 5 — BOSS INCOMING',
  subtitle: 'Defend the central plaza',
  tone: 'bad',
  seconds: 4
});
What happens in gamebanner

Displays a dramatic glass announcement banner across the upper-center viewport with colored accent border and subtitle.

WAVE 5 — BOSS INCOMINGDefend the central plaza
eg.ui.hint(player | null, text: string | null)
cmd#

Show a subtle control or action hint pill near the bottom HUD (null clears it).

example.js
js
eg.ui.hint(player, 'Hold Shift to sprint · Press H to use a medkit');
What happens in gametoast

Shows a lightweight control/tip pill right above the bottom HUD bar without interrupting gameplay (pass null to clear).

HINT · Hold Shift to sprint · Press H to use a medkit
eg.ui.countdown(player | null, opts: CountdownOpts | null)
cmd#

Show a big 3, 2, 1, GO! countdown overlay in the center of the screen (null cancels it).

example.js
js
eg.ui.countdown(null, { seconds: 3, label: 'RACE STARTS IN', goText: 'DRIVE!', sound: true });
What happens in gamecountdown

Counts down 3... 2... 1... GO! in huge animated center-screen numerals with optional audio beeps.

3RACE STARTS IN
eg.ui.clear(player | null)
cmd#

Clear every game HUD, card, menu, window, banner, countdown and GPS waypoint for a player (null: everyone).

example.js
js
eg.ui.clear(player);
What happens in gameresult

Instantly wipes every custom HUD card, menu, window, banner, countdown, and GPS route for a clean slate.

UI ResetHUD, windows, menus, banners & GPS cleared cleanly
eg.ui.waypoint(player, at: point | null, opts?: { hint?: string, hintM?: number })
cmd#

Guide a player to a point with the GPS (null lets go of it). `hint` is shown once when they arrive within hintM metres.

example.js
js
const dest = eg.world.offset(player, 0, -350);
eg.ui.waypoint(player, dest, { hint: 'Arrived at drop-off!', hintM: 18 });
What happens in gameworld

Locks the player's GPS route line and minimap beacon onto a point and triggers a hint pill once within `hintM` metres.

GPS ACTIVE 350 m North Draws blue road route · Shows arrival hint at 18 m

eg.chat

Post game announcements, private clues, and team callouts straight into players' in-game chat feeds.

eg.chat.announce(text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })
cmd#

Post a game line into the chat window for everyone currently in this game.

example.js
js
eg.chat.announce(eg.t('{name} captured the flag!', { name: player }), { label: 'Flag Rush', tone: 'good' });
What happens in gamechat

Posts a formatted game event line directly into the in-game chat log of everyone in the match, translated per player.

Flag RushMira captured the flag!
eg.chat.tell(player, text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })
cmd#

Post a private game line into one player's chat window.

example.js
js
eg.chat.tell(player, eg.t('Secret stash clue: look behind the gas station.'), { label: 'Informant' });
What happens in gamechat

Posts a private message visible only in that one player's chat feed.

Informant (Private)Secret stash clue: look behind the gas station.
eg.chat.team(team: string, text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })
cmd#

Post a game line into the chat window of every player on one team.

example.js
js
eg.chat.team('blue', 'Blue base shield is at 25%!', { label: 'Comms', tone: 'warn' });
What happens in gamechat

Sends a tactical team-only chat alert exclusively to members of the named team.

Comms [Blue]Blue base shield is at 25%!

eg.audio

Library sound effects for players or locations, plus gamepad haptic rumble.

eg.audio.cue(player | null, id: string)
cmd#

Play a short sound from the library by id (for instance "ui.job_accept").

example.js
js
eg.audio.cue(player, 'ui.job_accept');
What happens in gameresult

Plays a crisp UI or feedback sound effect from the platform sound library for one player or everyone (null).

Audio Cue🔊 Plays "ui.job_accept" chime for player
eg.audio.cueNear(at: point, id: string, opts?: { radius?: number })
cmd#

Play a library sound for every player within `radius` metres of a point (150 by default, up to 1000).

example.js
js
eg.audio.cueNear(player, 'ui.job_deliver', { radius: 120 });
What happens in gameworld

Plays a spatial event sound for every player standing within `radius` metres of a landmark or explosion.

SFX 120 m Proximity Audio Cue Audible only to players within 120 m
eg.audio.rumble(player | null, opts?: { strength?: number, seconds?: number })
cmd#

Vibrate a player's gamepad controller (`strength` 0.1 to 1, `seconds` 0.05 to 2; ignored when using keyboard).

example.js
js
eg.audio.rumble(player, { strength: 0.8, seconds: 0.3 });
What happens in gameresult

Fires dual-motor haptic controller rumble on blasts, collisions, or heartbeats (safely ignored on keyboard/mouse).

Haptic Rumble🎮 Vibrates gamepad motors (0.8 strength · 0.3 s)

eg.scores

Weekly and all-time leaderboards, personal bests, and player rank lookups for your game.

eg.scores.add(player, points: number, opts?: { meters?: number, board?: string }): Promise<{ week: number, all: number, runs: number } | null>
async · Promise#

Add points to a signed-in player on this game's weekly and all-time boards. Resolves to their totals, or null for a guest. `board` names a board of your own to add to instead (a count of wins, say); it is not shown on the game's leaderboard.

example.js
js
const tot = await eg.scores.add(player, 150, { meters: 640 });
if (tot) eg.ui.toast(player, eg.t('Total score: {n}', { n: tot.all }), 'good');
What happens in gameresult

Adds points (and optional distance) to a signed-in player's weekly and all-time public game leaderboards.

+150 Points SavedWeekly 450 · All-time 1,920 · 8 runs
eg.scores.setBest(player, board: string, ms: number, opts?: { meters?: number }): Promise<{ best: number, before: number | null, improved: boolean, rank: number | null } | null>
async · Promise#

Keep a signed-in player's best (lowest) time in milliseconds on a board you name, such as one per track. Resolves to their best now, what it was before, whether this run improved it, and their place on that board; null for a guest.

example.js
js
const r = await eg.scores.setBest(player, 'sprint-1', 42_310, { meters: 1400 });
if (r && r.improved) eg.ui.toast(player, eg.t('New PB! Rank #{rank}', { rank: r.rank }), 'good');
What happens in gameresult

Records a player's lowest time in milliseconds on a custom board (e.g. per track) and returns whether they beat their PB.

New Personal Best!0:42.31 · Rank #2 on sprint-1
eg.scores.bestOf(player, board: string): Promise<number | null>
async · Promise#

A player's best time on one of your time boards, or null.

example.js
js
const pb = await eg.scores.bestOf(player, 'sprint-1');
if (pb != null) eg.ui.toast(player, eg.t('Your best: {s} s', { s: (pb / 1000).toFixed(2) }));
What happens in gamehud

Reads a signed-in player's fastest saved time on a named board so you can display target times on HUDs.

Target Time
Your Best42.31 s
eg.scores.record(board: string): Promise<number | null>
async · Promise#

The best time anyone has set on one of your time boards, or null.

example.js
js
const wr = await eg.scores.record('sprint-1');
if (wr != null) eg.ui.toast(player, eg.t('Track record: {s} s', { s: (wr / 1000).toFixed(2) }));
What happens in gamehud

Fetches the #1 fastest time anyone has ever set on a board to display a global ghost target to beat.

World Record
Course Record39.84 s
eg.scores.top(period: 'week' | 'all', limit?: number): Promise<{ rank: number, name: string, score: number, runs: number, meters: number }[]>
async · Promise#

The top of a board.

example.js
js
const top = await eg.scores.top('week', 5);
eg.ui.menu(player, {
  id: 'lb', title: 'Weekly Top 5',
  rows: top.map(r => r.rank + '. ' + r.name + ' - ' + r.score + ' pts')
});
What happens in gamemenu

Queries the top ranked players on your weekly or all-time board to populate an in-game leaderboard window or menu.

Weekly Top 5✕
1. Mira - 1,420 pts
2. Leo - 1,180 pts
3. Sam - 940 pts
eg.scores.rankOf(player, opts?: { period?: 'week' | 'all', board?: string }): Promise<{ rank: number, score: number, runs: number } | null>
async · Promise#

A signed-in player's rank and total score on this game's weekly/all-time board or a custom board, or null.

example.js
js
const me = await eg.scores.rankOf(player, { period: 'week' });
if (me) eg.ui.toast(player, eg.t('Weekly rank #{rank} ({score} pts)', { rank: me.rank, score: me.score }));
What happens in gamehud

Looks up one signed-in player's exact leaderboard rank and score without fetching the entire leaderboard.

Your Standing
RANK #4 · 820 PTS

eg.saves

What your game keeps between sessions: a saved world's data in persistent games, and a little data per player in any game.

eg.saves.set(key: string, value: any)
cmdprivate games#

Keep a value with this saved world (persistent games: "instance": { "kind": "persistent" }). It is still there when players come back after everyone left, or after the server restarted: you get everything back in onLoad. Up to 200 keys and 256 KB per world.

example.js
js
const wave = (eg.state.wave || 1) + 1;
eg.state.wave = wave;
eg.saves.set('wave', wave);
What happens in gameresult

Persists world state across restarts in a `"kind": "persistent"` world (restored automatically in `onLoad`).

World SavedKey "wave" saved persistently (up to 200 keys / 256 KB)
eg.saves.get(key?: string): Promise<any>
async · Promiseprivate games#

One saved value of this world (null when there is none), or without a key everything saved, as { key: value }.

example.js
js
const all = await eg.saves.get();
eg.ui.toast(player, eg.t('World day {d}', { d: all.day || 1 }));
What happens in gametoast

Reads one saved key (or every key when omitted) from the persistent world storage at any point.

World day 14
eg.saves.remove(key: string)
cmdprivate games#

Forget one saved value of this world.

example.js
js
eg.saves.remove('tempContract');
What happens in gameresult

Deletes an obsolete key from persistent world storage to keep save data clean.

Save Key RemovedCleared "tempContract" from world save
eg.saves.setPlayer(player, key: string, value: any)
cmd#

Keep a value for this player in your game, in any kind of game: an unlock, a best time, where they left off. It follows them into every match and world of this game. Up to 50 keys and 16 KB per player.

example.js
js
const xp = ((await eg.saves.getPlayer(player, 'xp')) || 0) + 100;
eg.saves.setPlayer(player, 'xp', xp);
What happens in gameresult

Stores persistent progress (XP, unlocks, stats) for that player across every match or world of your game.

Player Progress SavedKey "xp" follows player across all matches
eg.saves.getPlayer(player, key?: string): Promise<any>
async · Promise#

One value kept for this player (null when there is none), or without a key everything kept for them.

example.js
js
const xp = (await eg.saves.getPlayer(player, 'xp')) || 0;
eg.ui.hud(player, [{ type: 'counter', text: 'Career XP', value: xp }]);
What happens in gamehud

Loads a player's saved unlocks or career XP when they join any lobby of your game.

Career
Career XP1400
eg.saves.removePlayer(player, key: string)
cmd#

Forget one value kept for this player.

example.js
js
eg.saves.removePlayer(player, 'activeBounty');
What happens in gameresult

Clears a saved key from one player's persistent data (e.g. resetting progress or completing a multi-session quest).

Player Key ClearedRemoved "activeBounty" from player save

eg.reports

A report of a round that its signed-in players and their organization can open later: each route on a map, with your numbers. The Response drill saves one after every drill.

eg.reports.save(report: { title: string, lines?: string[], points?: { label: string, at: point }[], players: { player: string, path?: [number, number, number][], stats?: { label: string, value: string }[] }[] }): Promise<{ id: string, url: string } | null>
async · Promise#

Save a report of the round that its signed-in players (and the admins of their organization) can open later: a map of each player's route (`path`: [lat, lon, seconds] points, up to 1500), their numbers, and your lines. `player` is a player's id. Show it with a card button whose action is "report" and whose id is the report id. Null when nobody signed in played. One report every 30 seconds per game.

example.js
js
const rep = await eg.reports.save({
  title: 'Drill Summary',
  lines: ['Target response time: 4:00'],
  players: [{ player: player.id, stats: [{ label: 'Time', value: '3:12' }] }]
});
if (rep) eg.ui.card(player, { title: 'Drill Complete', buttons: [{ id: rep.id, label: 'Open Report', action: 'report' }] });
What happens in gamecard

Generates a shareable post-match map & stats report page (`/reports/<id>`) that players can open in a single click.

Drill Complete Target response time: 4:00
Open Report

eg.instance

Inspect and control the running game itself: title, phase, locks, player cap, uptime, restarts, and shutdown.

eg.instance.setPhase(phase: string)
cmdprivate games#

Name the part of the game that is running ("lobby", "round 2", "over"). It is yours to choose; it is shown where the game is listed.

example.js
js
eg.instance.setPhase('wave 3');
What happens in gamehud

Updates the public phase label shown in the lobby browser and instance status.

Instance
PHASE: WAVE 3
eg.instance.setTitle(title: string)
cmdprivate games#

Update the running instance's live title shown in the instance bar.

example.js
js
eg.instance.setTitle('Night Shift · Wave 4');
What happens in gameresult

Updates the live match title displayed across everyone's top private-instance bar.

Instance Bar UpdatedTop bar now reads "Night Shift · Wave 4"
eg.instance.lock(locked?: boolean)
cmdprivate games#

Stop new players joining (a round is under way), or with false let them in again. Players already in the game are not affected.

example.js
js
eg.instance.lock(true);
eg.ui.toast(null, 'Match locked — round in progress.');
What happens in gametoast

Blocks new players from joining mid-round by invite code while keeping current players uninterrupted (`lock(false)` reopens).

Match locked — round in progress.
eg.instance.restart()
cmdprivate games#

Start the game over in place for a new round: the script starts again from onStart (after onLoad in a persistent game) with the players it has, and everything it put in the world is cleared. Saves are kept.

example.js
js
eg.ui.banner(null, { title: 'New Round Starting!', tone: 'good' });
eg.timers.after(3, () => eg.instance.restart());
What happens in gamebanner

Clears temporary entities/NPCs and restarts the script cleanly from `onLoad`/`onStart` with the same players inside.

New Round Starting!Restarting instance cleanly in 3 s
eg.instance.info(): { game: string, kind: string, title: string, version: string }
local#

About this running game.

example.js
js
const inf = eg.instance.info();
eg.ui.toast(player, eg.t('Welcome to {title} v{v}', { title: inf.title, v: inf.version }));
What happens in gametoast

Reads the running game's id, instance kind ("match" or "persistent"), title, and manifest version.

Welcome to Flag Rush v1.0.0
eg.instance.playersMax(): number
local#

Maximum number of players allowed in this running instance.

example.js
js
eg.ui.hud(player, [{ type: 'counter', text: 'Players', value: eg.players.count() + ' / ' + eg.instance.playersMax() }]);
What happens in gamehud

Returns the lobby capacity from `game.json` so lobby HUDs can display "4 / 8 players".

Lobby
Players4 / 8
eg.instance.isLocked(): boolean
local#

True when the instance is currently locked against new joins.

example.js
js
const state = eg.instance.isLocked() ? 'Locked' : 'Open';
eg.ui.toast(player, eg.t('Lobby is {state}', { state }));
What happens in gametoast

Lets scripts inspect whether the lobby currently accepts new arrivals before rendering lobby controls.

Lobby is Open
eg.instance.phase(): string
local#

The current phase string set by `instance.setPhase` (default "play" or "lobby").

example.js
js
if (eg.instance.phase() === 'lobby') {
  eg.ui.hint(player, 'Round starts once host confirms.');
}
What happens in gametoast

Returns the active phase label set by `instance.setPhase` so late joiners see the right onboarding prompt.

Round starts once host confirms.
eg.instance.uptimeS(): number
local#

Seconds since this running script started.

example.js
js
const mins = Math.floor(eg.instance.uptimeS() / 60);
eg.ui.toast(player, eg.t('Server uptime: {m} min', { m: mins }));
What happens in gamehud

Returns whole seconds elapsed since the instance script booted—useful for survival records or idle checks.

Match Time
Uptime12 min
eg.instance.end(reason?: string)
cmdprivate games#

End the game and send everyone back to the shared world.

example.js
js
eg.ui.toast(null, 'Match complete! Returning to world.', 'good');
eg.timers.after(4, () => eg.instance.end('finished'));
What happens in gametoast

Closes the private match and gracefully returns every player to the shared Free Roam world.

Match complete! Returning to world.

eg.timers

Schedule callbacks once or on an interval, inspect active timers, or clear them all at once.

eg.timers.after(seconds: number, fn: () => void): number
local#

Run a function once, later. Returns an id for timers.cancel.

example.js
js
eg.timers.after(5, () => {
  eg.ui.banner(null, { title: 'Gates Open!', tone: 'good' });
});
What happens in gamebanner

Schedules a one-off callback in `seconds` without risking frozen threads—ideal for round starts or delayed explosions.

Gates Open!Triggered after 5 seconds
eg.timers.every(seconds: number, fn: () => void): number
local#

Run a function again and again (at most ten times a second).

example.js
js
eg.state.tickId = eg.timers.every(1, () => {
  for (const p of eg.players.all()) eg.combat.heal(p, 2);
});
What happens in gamehud

Runs a repeating interval (down to 0.1 s) for capture ticks, poison hazards, or passive health regeneration.

Regen Aura
+2 HP / SEC
eg.timers.cancel(id: number)
local#

Stop a timer.

example.js
js
if (eg.state.tickId) {
  eg.timers.cancel(eg.state.tickId);
  eg.state.tickId = null;
}
What happens in gameresult

Stops a specific timer by id—essential when cancelling a bomb defuse or round clock early.

Timer CancelledStops repeating or pending callback immediately
eg.timers.cancelAll()
local#

Stop every active timer in this script at once.

example.js
js
eg.timers.cancelAll();
eg.ui.toast(null, 'Sudden pause — all timers cleared.');
What happens in gametoast

Stops every active `after` and `every` timer in one call when transitioning abruptly between phases.

Sudden pause — all timers cleared.
eg.timers.count(): number
local#

How many timers are currently active.

example.js
js
console.log('Active timers:', eg.timers.count());
What happens in gameresult

Counts active timers so you can verify cleanup and stay well inside the 500-timer sandbox limit.

Timer AuditActive timers: 3 / 500

eg.math

Convenient game math and randomness helpers: clamp, lerp, random integers, weighted loot rolls, shuffling, and seeded PRNGs.

eg.math.clamp(value: number, min: number, max: number): number
local#

Constrain a number between `min` and `max`.

example.js
js
const level = eg.math.clamp((eg.state.wave || 0) + 1, 1, 20);
What happens in gameresult

Keeps difficulty multipliers, scores, or speeds safely within bounded min/max limits.

Clamped Valueclamp(24, 1, 20) -> 20
eg.math.lerp(a: number, b: number, t: number): number
local#

Linearly interpolate from `a` to `b` by fraction `t` (0 to 1).

example.js
js
const speed = eg.math.lerp(4, 9, 0.5); // 6.5
What happens in gameresult

Smoothly blends difficulty, rewards, or enemy speeds between a start and end value as rounds progress.

Interpolatedlerp(4, 9, 0.5) -> 6.5
eg.math.randomInt(min: number, max: number): number
local#

A random whole number from `min` through `max` (inclusive).

example.js
js
const bonus = eg.math.randomInt(25, 100);
eg.ui.toast(player, eg.t('Found +{n} bonus points!', { n: bonus }), 'good');
What happens in gametoast

Rolls an inclusive random integer for loot payouts, dice games, or wave sizes.

Found +72 bonus points!
eg.math.pick(list: any[]): any
local#

Return one random element from an array, or null when empty.

example.js
js
const wx = eg.math.pick(['clear', 'rain', 'fog', 'storm']);
eg.world.setWeather(wx);
What happens in gameworld

Picks a random entry from any array (weather presets, spawn points, loot weapons, or quips).

PICKED: FOG Random Selection Picks uniformly from your array
eg.math.shuffle(list: any[]): any[]
local#

Return a new randomly shuffled copy of an array without mutating the original.

example.js
js
const order = eg.math.shuffle(eg.players.all());
order.forEach((p, i) => eg.ui.toast(p, eg.t('Turn #{n}', { n: i + 1 })));
What happens in gametoast

Creates a fair, unbiased random ordering of players, checkpoints, or card decks without mutating the source array.

Turn #2
eg.math.weighted(entries: { item: any, weight: number }[]): any
local#

Pick one item at random proportional to positive `weight` values, or null when empty.

example.js
js
const prize = eg.math.weighted([
  { item: 'bat', weight: 60 },
  { item: 'pistol', weight: 30 },
  { item: 'shotgun', weight: 10 }
]);
eg.inventory.give(player, prize, prize === 'bat' ? 1 : 18);
What happens in gamehud

Rolls rarity-weighted loot tables so common gear drops often while rare shotguns feel exciting.

Supply Crate
ROLLED: PISTOL (30%)
eg.math.seed(seed: string | number): () => number
local#

Create a fast, deterministic random number generator returning numbers between 0 and 1.

example.js
js
const rng = eg.math.seed('daily-' + Math.floor(eg.world.now() / 86400000));
const dist = 80 + rng() * 200;
What happens in gameresult

Creates a deterministic RNG stream so daily challenges or shared seeds produce identical spawns every run.

Deterministic SeedSame seed yields identical sequence across matches

HUD parts

Pieces you pass in an array to eg.ui.hud(player, parts). Text strings may hold {dist:1234}, {km:2.5}, or {time:95}, formatted automatically in each player's chosen units.

{ type: 'title' } with { text }
local#

The card's heading.

example.js
js
eg.ui.hud(player, [{ type: 'title', text: 'Flag Rush' }]);
What happens in gamehud

Draws the bold heading line at the top of the player's floating HUD card.

Flag Rush
{ type: 'text' } with { text }
local#

A line of text.

example.js
js
eg.ui.hud(player, [{ type: 'text', text: 'Reach the checkpoint before {time:90}' }]);
What happens in gamehud

Displays a formatted text line supporting automatic unit/time tokens (`{dist:1234}`, `{km:2.5}`, `{time:95}`).

Objective
Reach the checkpoint before 1:30
{ type: 'badge' } with { text, tone?: 'info' | 'good' | 'warn' | 'bad' }
local#

A colored status pill on the HUD card.

example.js
js
eg.ui.hud(player, [{ type: 'badge', text: 'OVERTIME', tone: 'warn' }]);
What happens in gamehud

Renders a vivid pill tag (`info`, `good`, `warn`, or `bad`) on the HUD card to highlight status at a glance.

Status
OVERTIME
{ type: 'distance' } with { to: point, text? }
local#

Live distance from the player to a point, in their units, then the text.

example.js
js
const goal = eg.world.offset(player, 240, 0);
eg.ui.hud(player, [{ type: 'distance', to: goal, text: 'to extraction' }]);
What happens in gamehud

Live-updates the exact remaining distance every navigation tick in the player's preferred metric or imperial units.

Extraction
240 m to extraction
{ type: 'bearing' } with { to: point, text? }
local#

Live compass direction and distance from the player to a point.

example.js
js
const target = eg.world.offset(player, 180, -180);
eg.ui.hud(player, [{ type: 'bearing', to: target, text: 'to beacon' }]);
What happens in gamehud

Live-updates a compass cardinal direction plus distance (e.g. "NE · 255 m to beacon") as the player moves.

Signal Hunt
NE · 255 m to beacon
{ type: 'timer' } with { since?: ms, until?: ms, par?: seconds, text? }
local#

A running clock: time since a moment (with an optional par), or time left until one.

example.js
js
eg.ui.hud(player, [{ type: 'timer', until: eg.world.now() + 60_000, text: 'left' }]);
What happens in gamehud

Ticks smoothly client-side every second using the synced server clock (`since` counts up with optional `par`, `until` counts down).

Round
⏱0:59 left
{ type: 'bar' } with { value, max, text? }
local#

A progress bar.

example.js
js
eg.ui.hud(player, [{ type: 'bar', value: 3, max: 5, text: 'Checkpoints 3 / 5' }]);
What happens in gamehud

Draws an animated horizontal progress bar filled proportionally to `value / max` with an optional overlay caption.

Route
Checkpoints 3 / 5
{ type: 'counter' } with { text, value }
local#

A labelled number.

example.js
js
eg.ui.hud(player, [{ type: 'counter', text: 'Wave', value: 4 }]);
What happens in gamehud

Pairs a muted label with a crisp emphasized number or short readout value.

Survival
Wave4
{ type: 'list' } with { items: { label, value?, highlight? }[] }
local#

A compact multi-row status list or mini scoreboard inside the HUD (up to 6 rows).

example.js
js
eg.ui.hud(player, [{
  type: 'list',
  items: [
    { label: '1. Mira', value: 420, highlight: true },
    { label: '2. Alex', value: 380 }
  ]
}]);
What happens in gamehud

Shows a compact multi-row leaderboard or checklist (up to 6 rows) directly inside the HUD card.

Standings
  • 1. Mira420
  • 2. Alex380
{ type: 'divider' } with {}
local#

A thin horizontal separator line between sections of the HUD card.

example.js
js
eg.ui.hud(player, [
  { type: 'title', text: 'Heist' },
  { type: 'divider' },
  { type: 'counter', text: 'Loot', value: '$1,200' }
]);
What happens in gamehud

Inserts a crisp horizontal divider line to visually separate sections inside longer HUD cards.

Heist

Loot$1,200
{ type: 'button' } with { id, label, action?: 'signin' | 'waypoint' | 'close' | 'report' }
local#

A button. Fires onUi { from: "hud", id }, or does a built-in action ("report": opens the saved report whose id is the button id).

example.js
js
eg.ui.hud(player, [{ type: 'button', id: 'shop', label: 'Open Shop' }]);
What happens in gamehud

Places a clickable button right on the HUD card that sends `onUi` (`from: "hud"`) or runs built-in actions (`signin`, `waypoint`, `close`, `report`).

Quick Action
Open Shop
{ type: 'teams' } with {}
local#

The teams and their scores as they are when you send it, the player's own team marked.

example.js
js
eg.ui.hud(player, [{ type: 'teams' }]);
What happens in gamehud

Renders color-coded pill badges for every defined team and its score, highlighting the viewing player's own team.

Match Score
Red 6Blue 4

eg.state

A plain JavaScript object that stays yours for the lifetime of the running game instance.

eg.state: Record<string, any>
local#

Persistent per-instance memory across timers and event handlers until the instance closes or restarts.

example.js
js
eg.state.round = (eg.state.round || 0) + 1;
eg.state.scores = {};
eg.ui.toast(null, eg.t('Round {n} begin!', { n: eg.state.round }));
What happens in gameresult

A plain JavaScript object preserved in memory across all event handlers for as long as the match runs (cleared on restart/close).

In-Memory Match StateFast synchronous state shared across every handler

eg.t

Text players see, in each player's own language. How it works, step by step: Translating your game.

eg.t(text: string, values?: { [name: string]: string | number | Player }): string
local#

Text players see, in English with its values filled in, marked so that each player gets it in their own language: eg.ui.toast(player, eg.t('{n, plural, one {# flag} other {# flags}} to go', { n })). Write the text out in quotes where you call it; put the parts that change in as {names} (a player becomes their name). Use the result anywhere players see text: toasts, the HUD, cards, menus, labels, waypoint hints. Translations come from your lang/<code>.json files and, once the game is live and played, from the platform.

example.js
js
const left = 3;
eg.ui.toast(player, eg.t('{n, plural, one {# flag} other {# flags}} remaining', { n: left }), 'good');
What happens in gametoast

Marks text for per-player translation (from `lang/*.json` or live AI translations) while rendering English + ICU plurals automatically.

EN: 3 flags remaining · FR: 3 drapeaux restants