No API entries match your current search or filter.
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 })
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.
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
The game started (or restarted after the server did). Set things up here.
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.
onPlayerJoin(player, info: { rejoined: boolean })
A player entered the game. `rejoined` is true when they came back after a dropped connection in time to keep their place.
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.
A player's connection dropped and their place is being held for a while (manifest player.rejoinS). Pause what they were doing.
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')
A player is gone from the game for good.
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.
onPlayerArea(player, area: { id: string, center: point })
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.
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 })
A player switched how they are getting around (for instance walk to drive, or drive to walk).
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')
A player entered or left a zone with a trigger, or stayed in it slowly enough for long enough (dwell).
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)
A player pressed F at an entity with `interact`.
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 })
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).
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`).
onPlayerDamaged(player, hit: { amount: number, hp: number, why: 'npc' | 'player' | 'blast' | string, by?: string, npc?: number, kind?: string, weapon?: string })
A player lost health. `by` is the id of the player responsible, `npc` the character.
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.
onPlayerDied(player, hit: { why: string, by?: string, npc?: number, kind?: string, weapon?: string })
A player reached 0 health and is down.
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.
A downed player is back on their feet.
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.
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 })
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.
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 })
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.
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.
eg.world
Time, distance, bearings, real places, and instance weather/solar-hour atmosphere. Everything works wherever on Earth the game is played.
The time now, in milliseconds since 1970 (the server clock).
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.
eg.world.distance(a: point, b: point): number
Metres between two points.
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
The point that many metres east and south of another: place things relative to wherever the game is being played.
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 solar hour (0 to 24) at a point, for "only at night" rules anywhere on Earth.
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[]>
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).
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>
Is this point on a road? null where the map is not built.
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
Compass bearing in degrees from one point toward another (0 north, 90 east, 180 south, 270 west).
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.
eg.world.pointAlong(from: point, bearingDeg: number, meters: number): point
The point `meters` away from `from` along a compass bearing in degrees.
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
The point halfway between two points.
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
True when `at` is within `radiusM` metres of `center`.
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.
eg.world.randomPoint(center: point, opts?: { minM?: number, maxM?: number }): point
A random point evenly distributed inside a circle or ring (`minM` to `maxM` metres, default 0 to 100) around `center`.
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)
Override the weather ("clear", "cloudy", "overcast", "rain", "storm", "snow", "fog") for everyone in the instance (null restores live local weather).
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)
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).
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)
Flash the sky and play thunder for players near a point, or everyone in the instance when omitted.
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[]
Everyone in the game now.
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
The latest snapshot of one player, or null when they are not in the game.
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[]
Players within a radius of a point, nearest first.
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
The closest player to a point matching optional filters (`exclude`, `team`, `alive`, `maxM`), or null when none match.
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[]
Everyone currently assigned to a team.
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
One randomly chosen player matching optional filters, or null when none match.
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
How many players are in the game.
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
True when the player is marked busy with `players.setBusy` or in a race.
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.
eg.players.setData(player, key: string, value: any)
Keep an ephemeral value on a player for this run (up to 50 keys per player; cleared when they leave).
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.
eg.players.getData(player, key?: string): any
Read one ephemeral value set with `players.setData` (or all keys as an object when `key` is left out).
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).
eg.players.skipped(player, sinceMs: number): 'teleport' | 'correct' | 'fly' | null
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.
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)
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.
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.
eg.players.startRun(player): Promise<boolean>
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.
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.
eg.players.finishRun(player)
A run that began with startRun was completed. Counts as having played the game.
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.
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)
Move a player to a point at once: the start of a round, a respawn point.
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 })
Move everyone in the instance to a point, optionally spaced evenly around a ring of `spreadM` metres (0 to 100).
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)
Freeze or unfreeze a player (null: everyone). Frozen players cannot walk or drive, while still able to look around and answer prompts or windows.
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.
Put a player out of the vehicle they are driving onto foot beside it.
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)
Send a player out of this private instance back to the shared world with an optional message.
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.
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.
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.
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.
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' }[])
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.
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)
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.
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
Put every player who has no team on the team with the fewest players.
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)
Add to a team's score (a negative number takes away).
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.
eg.teams.setScore(team: string, points: number)
Set a team's score.
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.
eg.teams.all(): Promise<Team[]>
The teams now, with their scores and the ids of the players on each.
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>
One team by id, with its color, score and player ids, or null.
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.
eg.teams.leader(): Promise<(Team & { tied: boolean }) | null>
The highest-scoring team right now (`tied` is true when two or more teams share the lead), or null when no teams are defined.
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
Set every defined team's score back to 0.
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.
Randomly rebalance every player currently in the game evenly across the defined teams.
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')
Show a toast message only to players on one team.
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)
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.
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)
Set ground-vehicle handling for everyone in the instance: "arcade" (forgiving grip), "sport" (eager and lively), or "real" (factory road specs).
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)
Fit a tire compound ("slick", "allweather", "gravel", or null for default) on a player's vehicle or everyone's.
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)
Cap ground-vehicle speed in metres per second (for pit lanes or speed traps); null removes the cap.
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.
eg.vehicles.boost(player, opts?: { strength?: number, seconds?: number })
Give a player's ground vehicle a temporary speed and acceleration surge (`strength` 0.2 to 2, `seconds` 0.3 to 8).
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 })
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.
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)
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.
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)
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.
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[]>
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.
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.
eg.race.course(points: point[], opts?: { name?: string, laps?: number }): Promise<Track | null>
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.
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' }>
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.
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
Take a player out of the race they are lining up for or driving. You hear onRace with ev "void", reason "cancelled".
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".
eg.race.status(player): Promise<{ track: string, stage: 'grid' | 'count' | 'race', next: number, total: number } | null>
The race a player is currently in (`stage`, `next` gate and `total` gates), or null when they are not racing.
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.
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
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.
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)
Change an entity (same fields as add).
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)
Take an entity off the map.
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>
Read one entity your script placed by id, or null when it is not on the map.
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[]>
List the entities your script currently has on the map, optionally filtered by `kind`, id `prefix` or `visibleTo`.
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.
eg.entities.near(at: point, radiusM: number, opts?: { kind?: 'zone' | 'marker', prefix?: string }): Promise<Entity[]>
Your script's entities within `radiusM` metres of a point, nearest first.
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>
How many entities your script currently has on the map.
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 })
Remove every entity your script placed, or only those matching an id `prefix` or `visibleTo`.
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[])
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? } }].
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.
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).
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)
Take a character out of the world at once.
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.
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.
Remove every character.
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 })
Change what a character is doing.
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.
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.
eg.npcs.damage(id: number, amount: number, by?: player): Promise<{ hp: number, died: boolean } | null>
async · Promiseprivate games#
Hurt a character.
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)
Heal a character.
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 }.
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.
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.
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.
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 } })
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.
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 })
Remove a spawner; `clear` also removes the characters it made.
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)
Switch a spawner on or off.
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)
Scale a spawner (0 none, 1 as written, up to 4).
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)
Spawn up to n right now, ignoring the rate.
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)
Remove the characters a spawner made.
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.
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 })
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.
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
Switch combat off: weapons are put away and nobody can be hurt by shots. Health and inventories are kept.
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)
Let players hurt each other, or stop them.
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)
Set a player's health (and, optionally, their maximum). 0 kills them.
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.
eg.combat.setArmor(player, armor: number)
Set a player's armor, 0 to 100. Armor soaks 60 % of each hit until it is used up.
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.
eg.combat.setSafe(player, seconds: number)
Give a player `seconds` (0 to 60) of spawn protection during which attacks do not hurt them.
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.
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.
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)
Give health back, up to their maximum. Call it from a timer for health that comes back by itself.
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)
Heal every living player in the game (by `amount`, or back to full health when left out).
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)
Put a player down at once.
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)
Put a downed player back on their feet now, with full health.
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.
Put every downed player in the game back on their feet now with full health.
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)
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).
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)
Take some of an item away, or all of it when count is left out.
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.
eg.inventory.setLoadout(player, loadout: Loadout)
Replace everything a player carries: { pistol: 48, bat: 1, medkit: 2 }. Everyone always has fists.
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)
Put a weapon they carry in their hands.
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.
eg.inventory.get(player): Promise<{ [item: string]: number }>
async · Promiseprivate games#
What a player carries now.
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.
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.
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.
eg.inventory.clear(player)
Remove everything from a player's inventory, leaving only fists.
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.
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 })
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.
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 })
A puff of dust, as when something hits the ground or a wall.
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 })
A burst of sparks.
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 })
Smoke rising from a point for a few seconds.
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 })
Flickering flames rising at a point for `seconds` (2 by default, up to 12).
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 })
A celebratory burst of colorful confetti around a point or player.
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 })
An expanding shockwave or pulse ring on the ground.
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 })
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.
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 })
Flash the edges of a player's screen (null: everyone).
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')
A short message. null sends it to everyone in the game.
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.
eg.ui.hud(player | null, parts: HudPart[] | null)
Set a player's HUD card for this game (null clears it). See HUD_PARTS for the pieces.
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.
eg.ui.card(player, card: { title: string, lines?: string[], buttons?: Button[], seconds?: number } | null)
A result card (shown in place of the HUD until closed or `seconds` pass).
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.window(player | null, win: WindowDef | null)
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".
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
✕
Silent EntryStay off cameras until the vault opens.
Ready UpLater
eg.ui.closeWindow(player | null, id?: string)
Close one open window by id, or all open windows when `id` is omitted.
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>
Open a Yes/No modal dialog for one player and await their answer (`true` when confirmed, `false` when cancelled, closed or timed out).
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>
Open a text-input modal dialog for one player and await what they type (up to 240 characters), or `null` when cancelled.
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>
Open a choice/dialogue picker modal for one player and await the chosen option's `id`, or `null` when cancelled.
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>
Open a multi-field modal form (`text`, `number`, `select`, `checkbox`, `slider`, up to 8 fields) and await `{ [name]: value }`, or `null` when cancelled.
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)
Show a bold announcement banner across the upper center of the screen (null clears it).
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)
Show a subtle control or action hint pill near the bottom HUD (null clears it).
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)
Show a big 3, 2, 1, GO! countdown overlay in the center of the screen (null cancels it).
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.
eg.ui.clear(player | null)
Clear every game HUD, card, menu, window, banner, countdown and GPS waypoint for a player (null: everyone).
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 })
Guide a player to a point with the GPS (null lets go of it). `hint` is shown once when they arrive within hintM metres.
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 })
Post a game line into the chat window for everyone currently in this game.
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 })
Post a private game line into one player's chat window.
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 })
Post a game line into the chat window of every player on one team.
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)
Play a short sound from the library by id (for instance "ui.job_accept").
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 })
Play a library sound for every player within `radius` metres of a point (150 by default, up to 1000).
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 })
Vibrate a player's gamepad controller (`strength` 0.1 to 1, `seconds` 0.05 to 2; ignored when using keyboard).
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>
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.
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>
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.
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>
A player's best time on one of your time boards, or null.
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>
The best time anyone has set on one of your time boards, or null.
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 }[]>
The top of a board.
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.
eg.scores.rankOf(player, opts?: { period?: 'week' | 'all', board?: string }): Promise<{ rank: number, score: number, runs: number } | null>
A signed-in player's rank and total score on this game's weekly/all-time board or a custom board, or null.
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)
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.
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 }.
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.
eg.saves.remove(key: string)
Forget one saved value of this world.
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)
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.
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>
One value kept for this player (null when there is none), or without a key everything kept for them.
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.
eg.saves.removePlayer(player, key: string)
Forget one value kept for this player.
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>
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.
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)
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.
eg.instance.setPhase('wave 3');
What happens in gamehud
Updates the public phase label shown in the lobby browser and instance status.
eg.instance.setTitle(title: string)
Update the running instance's live title shown in the instance bar.
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)
Stop new players joining (a round is under way), or with false let them in again. Players already in the game are not affected.
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.
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.
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 }
About this running game.
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
Maximum number of players allowed in this running instance.
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".
eg.instance.isLocked(): boolean
True when the instance is currently locked against new joins.
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.
eg.instance.phase(): string
The current phase string set by `instance.setPhase` (default "play" or "lobby").
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
Seconds since this running script started.
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.
eg.instance.end(reason?: string)
End the game and send everyone back to the shared world.
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
Run a function once, later. Returns an id for timers.cancel.
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
Run a function again and again (at most ten times a second).
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.
eg.timers.cancel(id: number)
Stop a timer.
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
Stop every active timer in this script at once.
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
How many timers are currently active.
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
Constrain a number between `min` and `max`.
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
Linearly interpolate from `a` to `b` by fraction `t` (0 to 1).
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
A random whole number from `min` through `max` (inclusive).
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.
eg.math.pick(list: any[]): any
Return one random element from an array, or null when empty.
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[]
Return a new randomly shuffled copy of an array without mutating the original.
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.
eg.math.weighted(entries: { item: any, weight: number }[]): any
Pick one item at random proportional to positive `weight` values, or null when empty.
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
Create a fast, deterministic random number generator returning numbers between 0 and 1.
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 }
The card's heading.
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.
{ type: 'text' } with { text }
A line of text.
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' }
A colored status pill on the HUD card.
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.
{ type: 'distance' } with { to: point, text? }
Live distance from the player to a point, in their units, then the text.
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? }
Live compass direction and distance from the player to a point.
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? }
A running clock: time since a moment (with an optional par), or time left until one.
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).
{ type: 'bar' } with { value, max, text? }
A progress bar.
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.
{ type: 'counter' } with { text, value }
A labelled number.
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.
{ type: 'list' } with { items: { label, value?, highlight? }[] }
A compact multi-row status list or mini scoreboard inside the HUD (up to 6 rows).
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.
{ type: 'divider' } with {}
A thin horizontal separator line between sections of the HUD card.
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.
{ type: 'button' } with { id, label, action?: 'signin' | 'waypoint' | 'close' | 'report' }
A button. Fires onUi { from: "hud", id }, or does a built-in action ("report": opens the saved report whose id is the button id).
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`).
{ type: 'teams' } with {}
The teams and their scores as they are when you send it, the player's own team marked.
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.
eg.state
A plain JavaScript object that stays yours for the lifetime of the running game instance.
eg.state: Record<string, any>
Persistent per-instance memory across timers and event handlers until the instance closes or restarts.
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
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.
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