Systems
Each fixed step runs the world’s systems in order. A system is a function of the step, (step) => void, made with defineSystem. Its step.world is a World, which reads and never writes: a system writes through its step, as Writing a trait says. The step holds its length in deltaSeconds, its number in tick, the player’s input, and authoritative, which says whether this world decides outcomes. A game adds one in a plugin, under the phase it runs in.
A system runs in one of the step’s four phases, input, motion, rules and physics, and a plugin’s systems says how the step orders the phases and the systems within each. core’s reference page tables every engine system by phase, in the order the step runs them.
A system creates no three.js object or array on each call. world.query builds an array and records, so use the engine’s passes for a system’s query, as the behaviour scaffold’s FeatureSystem.ts on Templates does.
Import createQuery from the engine and make the query once. updateEach(step, query, callback) writes records; readEach(world, query, callback) reads them.
updateEach refuses a query of predicted traits; use step.updateEachPredicted for those. readEach returns read-only records. Each pass reuses its callback’s tuple, so keep a field rather than the tuple.
findEntity finds the first entity a query matches, and readField reads one field of one trait; neither builds anything. A game’s lint reports world.query in a system, engine/system-query: in a function a definePlugin call in the same file names under systems, a variable typed System, or a function that takes a step or the step’s options.
The step’s profile names each system as its plugin names it, plugin.system, such as core.physics or regeneration.heal. The devtools’ wiki shows the line the entry’s description gives beside that name. A headless game times its systems once its world has the StepProfileTrait trait, and readStepProfile(game.world) reads the times. spawnite simulate steps the scene on the plugins list the scene’s file exports, else on the one src/game.ts exports, else on the building blocks alone; --profile times that step.
Writing a trait
Section titled “Writing a trait”A system writes a trait through five verbs and a walk, each taking what may write first, as Unity’s EntityManager.SetComponentData takes the entity manager:
setTrait(step, entity, Trait, value)sets the fields given. A trait made from a function keeps its own record, and the value is copied into it, so a vector the system goes on using never becomes the record’s.editTrait(step, entity, Trait)hands the record to change in place, such as a vector or a list in it. It tells no watcher, such as a view’suseTrait, of the change:setTraitdoes. The record is the system’s until the system returns: in development, a write through it after that throws, so take it again in the system that writes.updateEach(step, query, callback)walks a query and hands each entity’s records to write in place.addTrait(step, entity, Trait, value)adds a trait the entity does not hold, andremoveTrait(step, entity, Trait)takes one off, inside a walk too.addOrSetTrait(step, entity, Trait, record)adds the trait where the entity lacks it and sets it where it holds it, such as a poison a second hit starts again. It returnstruewhere it added. It takes the whole record, every field, so the trait ends the same whether it was added or set. A tag takes no record.
Each takes the world in place of the entity for a trait on the world. In development, setTrait on a trait the entity does not hold throws, and addTrait on one it holds throws, each naming the other and addOrSetTrait. To change some fields of a trait the entity may lack and keep the rest, ask entity.has(Trait) first.
A walk visits the entities as they stood when it began, so a callback may add, remove, spawn and destroy(step, entity) as it goes:
- An entity spawned during the walk waits for the next one.
- An entity destroyed during the walk is skipped when its turn comes, whatever destroyed it. The callback’s index keeps each entity’s place in the list, so a skipped one leaves a gap.
- An entity that lost a trait of the query during the walk is still handed, with the record it held.
- Inside a player’s
onPlayerLeave, a destroy waits until the player’s leave hooks end, so a walk there still hands the entity.
The first argument is the writer, and the writer you hold decides what you may write:
| Writer | Where it comes from | What it writes |
|---|---|---|
| The room’s step | A system with no runsOn, or inside if (step.authoritative) |
Any trait |
| Any other step | A system that runs on a page | Reach.Local and Reach.Authority traits; through updateEach, any trait of the page’s own entities |
| The predicted step | A predicted system, on the entity step.updateEachPredicted hands out |
Predicted traits, as Predicted systems shows |
| An authority | useAuthorityEffect((authority) => …) in a logic component |
Any trait, where the world decides outcomes |
| A destroy hook’s writer | onEntityDestroy’s context, through findAuthority(writer, entity) |
Any trait, where the world decides outcomes; the page’s own entities on a page |
| A plugin’s setup writer | setup(world, writer), as Plugins shows |
Any trait, while setup runs |
| A logic component’s setup | useSetupEffect((writer) => …, deps) |
Any trait, while the effect and its cleanup run; on a page in a room, none the room streams |
| A view’s writer | useViewWriter() in a view or in the game’s own HUD |
Reach.Local traits, between steps, while the view is mounted |
A Reach.Local trait is the page’s own, on any entity, one the room streams among them. A view sends a command for the rest, as Logic and views says.
The engine’s own write functions take the writer first in the same way, such as addStatModifier(step, character, moveSpeedStat, modifier) and random(step). startCooldown(step, entity, { key, seconds }) starts a cooldown under a key from defineCooldown(name), or defineCooldown(name, { scope }) for a plugin’s own key, on a game that lists cooldowns(), and isCoolingDown(entity, key) reads it. Start one on the player’s character from a predicted system, and one a room rule decides on another entity, such as the player entity, as Cooldowns says. teleport(step, entity, { position }) moves an entity to a place at once, as Moving a body says. A read takes the world or the entity alone, such as findTeam(world, player) for the player’s team, as Teams lists. A step writes only inside the system it was handed to: one kept in a variable and written with later throws, and so does a join’s step once its hooks end.
Systems and the modules they share import from @spawnite/engine/core, and a file with React components from @spawnite/engine. Both export the same World and Entity types; @spawnite/engine also exports the <Entity> component under the name of its type, as React’s Component is a value and a type.
The entity a game holds, Entity from the engine, reads and never writes: get returns its record read-only, and it has none of koota’s set, add, remove or destroy. A game’s lint refuses koota’s own writes, and an import of koota or koota/react in src, so the verbs are the one way to write. The types a game names beside them come from the engine too: Trait, TagTrait, Schema, Query and QueryParameter, as an editor shows them.
A defineTrait field may hold an entity, such as the sample’s poisoner: null as Entity | null, or a list of entities, each named in the trait’s entities option, as Choose who a trait reaches says.
To add a trait or start it again where the entity holds it, write it with addOrSetTrait. The sample keeps its timers as ticks, as A timer of a game’s own says. A rule the room decides runs with no runsOn, so its step is the room’s, as this one does:
import type { Entity } from "@spawnite/engine/core";import { addOrSetTrait, createQuery, DamagedEvent, dealDamage, definePlugin, defineTrait, DiedEvent, DownedTrait, readEach, readEvents, readTickAfterSeconds, removeTrait, setTrait, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";import { behaviours } from "@spawnite/engine/behaviours";// A room's rule: a hit from the weapon named "venom" poisons what it hit// for five seconds, five health a second, and a second hit starts the five// seconds again. Each tick is credited to the poisoner.
/** A poisoned entity: the tick the poison ends on, the tick its next damage * lands on, and who poisoned it, named in `entities` so a destroy sets it * to null. The room streams it, so a page can draw it. */export const PoisonedTrait = defineTrait( "outsidePoisoned", { endTick: 0, nextDamageTick: 0, poisoner: null as Entity | null, }, { entities: ["poisoner"] },);
const poisoned = createQuery(PoisonedTrait);
function poisonOnHit(step: AuthoritativeStep) { // A death ends the poison. This runs before the reap, so each death // it reads came before each hit it reads: a hit after a respawn of no // wait poisons the body that stood again. // ponytail: a game's own system placed between this one and the reap // breaks that order; an ordered read of two kinds of event lifts it. for (const { entity } of readEvents(step, DiedEvent)) if (entity?.has(PoisonedTrait)) removeTrait(step, entity, PoisonedTrait); for (const { entity, record } of readEvents(step, DamagedEvent)) { // The weapon's name, as registerWeapon gave it; the poison's own // ticks carry none, so they poison nothing again. A downed body // waits for its respawn, so a hit there poisons nothing. if (!entity || record.weapon !== "venom" || entity.has(DownedTrait)) continue; // A second hit keeps the next damage's tick, so a weapon that hits // faster than once a second still deals the poison. const nextDamageTick = entity.get(PoisonedTrait)?.nextDamageTick ?? readTickAfterSeconds(step, 1); addOrSetTrait(step, entity, PoisonedTrait, { endTick: readTickAfterSeconds(step, 5), nextDamageTick, poisoner: record.source, }); }}
function tickPoison(step: AuthoritativeStep) { // The trait is written as damage lands, once a second, and on no step // between, as the Systems page advises for a timer. readEach(step.world, poisoned, ([poison], entity) => { const { endTick, nextDamageTick, poisoner } = poison; if (step.tick >= nextDamageTick) { setTrait(step, entity, PoisonedTrait, { nextDamageTick: readTickAfterSeconds(step, 1), }); // Credited to the poisoner, so DiedEvent's source names it for a // kill, and judged by the poisoner's team as it lands; once the // poisoner is gone, by no one's. dealDamage(step, entity, { amount: 5, source: poisoner }); } // Safe inside the walk, which walks the list as it began. if (step.tick >= endTick) removeTrait(step, entity, PoisonedTrait); });}
const reap = behaviours.systems.reapDead;
export const poison = definePlugin(() => ({ name: "poison", description: "A venom hit poisons for five seconds.", // No runsOn: the room alone runs them, with its own step. systems: [ // Both before the reap: readEvents gives no order between two // kinds of event, so the anchor gives the hits and deaths one, // and no tick lands on a body that died and stood again. defineSystem({ name: "poisonOnHit", phase: Phase.Rules, before: [reap], run: poisonOnHit, }), defineSystem({ name: "tickPoison", phase: Phase.Rules, before: [reap], run: tickPoison, }), ],}));A room judges an instant shot as the shot’s message arrives, between two steps, so every system of the next step reads its DamagedEvent. A projectile’s hit from weapons.flyProjectiles and a shot in a game played alone from weapons.takeFireCommands land during rules, among the engine’s systems. A game’s own rules system runs after them and reads them in the same step. A before anchor on an engine system earlier in rules, such as the poison’s before: [behaviours.systems.reapDead], places it ahead of them, and it then reads them the next step.
The poison reads two kinds of event, and readEvents gives no order between two kinds, so its anchor gives it one. Ahead of the reap, each DiedEvent it reads came before each DamagedEvent it reads, unless a game’s own system that deals damage runs between it and the reap. So it ends the poison of the dead first, then poisons on each venom hit, and a hit that lands after a respawn of no wait, in the step of the death, poisons the body that stood again. A player’s character, or anything with a respawn, is downed and kept rather than destroyed, which is why the poison ends on the event and not on the entity’s removal.
The sample credits each tick to its poisoner, so a kill’s DiedEvent names the poisoner’s character, player entity and team. Each tick is judged and credited by the poisoner’s team as it lands, as Friendly fire says.
Answering a command
Section titled “Answering a command”A system answers the commands a page sends. Its entry names each command’s key in answers, such as answers: ["plant"], and the system reads them with readCommands(step, plugin.commands.plant). A command no system answers throws as the world is made. In development, a system that reads a command its entry does not list throws at the read. defineCommand takes no name: the plugin names the command by its key under commands, and hands back its handle there. Send the room a command says how to declare, read and settle one.
When a system throws
Section titled “When a system throws”What a throw does depends on where the system runs:
- On a room the platform hosts, the room catches the throw at the system. The rest of that system’s tick is skipped, while what it wrote before the throw stays, and the step runs the systems after it. The system runs again next tick. The room logs a
systemFaultedline naming the system, the tick, the message and the stack. It logs each message once per heartbeat, and at most four per system. The heartbeat counts every throw by system, so a system that fails every tick shows a count equal to the room’s steps. - In a development room, the throw closes the room, so you see it at once. The room stores every player’s save first, logs a
failedline with the stack, and closes each page withroomFailedCloseCode. Its reason, read withreadRoomFailedReason, says whether the player’s save was stored. The player’s page joins again as a new player when the room starts again, and that join loads the player’s save. - In a headless test or
spawnite simulate, the step throws, as any function does.
A spawn a full world refuses, as A world’s size says, is the room’s refusal and no fault. On every room the rest of that system’s tick is skipped, and each command it held is refused "world-full". Nothing is logged as a fault, and development warns once for each system.
A system that throws midway may leave what it wrote half done for that tick. A throw from the room’s own work around the systems, such as its send or a save, closes even a hosted room, and every player’s save is stored first. A loop that never ends cannot be caught: it stops the whole room.
Where a system runs
Section titled “Where a system runs”In a game with a room, the room is the server and each player’s page is a client, the two ends that RunContext.Server and RunContext.Client name. This page calls them the room and the page. A system runs on the room alone unless its entry declares otherwise. The room judges the rule and streams the result, and each page draws it. Set runsOn on the entry to run the system elsewhere:
// Excerpt of src/moves.plugin.tsimport { definePlugin, defineSystem, Phase, RunContext,} from "@spawnite/engine/core";
export const moves = definePlugin(() => ({ name: "moves", systems: [ // Nothing declared: the room alone. defineSystem({ name: "scoreKills", phase: Phase.Rules, run: scoreKills, }), // Works out a `Reach.Local` trait on each end, which nothing rolls back. defineSystem({ name: "footing", phase: Phase.Rules, runsOn: RunContext.Both, run: readFooting, }), // Only draws, so the room skips it. defineSystem({ name: "trailSparks", phase: Phase.Rules, runsOn: RunContext.Client, run: trailSparks, }), ],}));The following table shows where each declaration runs:
runsOn |
The room | A page of a room | A game with no room |
|---|---|---|---|
Left out, or RunContext.Server |
Runs | Skipped | Runs |
RunContext.Both |
Runs | Runs | Runs |
RunContext.Client |
Skipped | Runs | Runs |
Declare RunContext.Both for a system the room and a page each run for themselves and that writes nothing the player’s page predicts, such as one that works out a Reach.Local trait. A system that writes what the player’s page predicts, the character’s velocity or any other predicted trait, is a predicted system instead: predicted: true runs it on both ends and again in a correction, as Predicted systems describes. A RunContext.Both system cannot write a predicted trait of yours, since Koota’s functions refuse one, and one that writes an anyEntity predicted trait of the character is reported by the prediction checks. A single-player game has one world that is both the room and the page, so it runs every system and needs no declaration.
A page’s world lacks the traits only the room holds, so a room’s rule that ran on a page would write from what is missing. The default keeps that rule off the page. Unreal runs gameplay code on the server unless a function is marked for a client, and Roblox runs a Script on the server and a LocalScript on a client. Unity’s Netcode and Godot leave the check to the code, with IsServer and is_multiplayer_authority().
The devtools’ wiki says where each system runs under its name.
An outcome, such as damage, a heal, loot or a score, runs only on the world that decides outcomes: the room, or a game with no room. The type holds this rule. Every outcome function takes an Authority first, dealDamage(step, target, { amount: 30 }) and dealHealing(step, target, { amount: 20 }), and only the room’s step is one:
- A system whose entry leaves
runsOnout receives the room’s step, anAuthoritativeStep, so it calls an outcome with no check. - A system that runs on both, or a predicted system, receives a step that may be the player’s page’s.
step.authoritativeis true on the room and in a game with no room, and false on a page in a room, andif (step.authoritative)narrows the step to the room’s. An outcome outside that check fails to typecheck, so a page that predicts a hit never deals it. - Code outside a step in a logic component writes as it mounts through
useAuthorityEffect((authority) => cleanup, dependencies), which hands the world’s authority only where outcomes are decided, as Logic and views says. A test holds aWritableWorldand callsrequireAuthority(world).isAuthoritative(world)says whether the world decides outcomes.isRoomWorld(world)says whether the world is a room’s own, the one its pages join, which a game played alone is not: a component that spawns what a room holds for its players, such as<Match>’s match, which waits there for the first page, asks it.
Give a game’s own outcome, such as a score, the same first parameter, authority: Authority, so its callers pass the room’s step too. Read its world from it with readAuthorityWorld(authority, "awardScore"), which throws, naming your function, for an authority no step and no requireAuthority made. Should a cast or a plugin in JavaScript get past the type, the engine’s outcome functions throw on a page in a room, naming the function and the fix. Every step also carries step.tick, the step’s number on the world’s clock. Unreal’s HasAuthority() and Roblox’s RunService:IsServer() answer the same question at run time; here the compiler asks it. A view holds no step, so a game’s lint reports an outcome the engine exports, such as addCoins or dealDamage, called from a component or a hook, engine/view-outcome: the page sends the room a command with sendCommand, and a system decides.
A page’s read of a room-only trait
Section titled “A page’s read of a room-only trait”A page of a room never holds a trait defined with reach: Reach.Authority. A system that runs there and reads one finds nothing, acts on that, and the room corrects what it did at every send, 60 or 30 times a second. In development, the page throws on the first such read instead, and names the system and the trait:
moves.sprint read "stride" on a page, where it never is: the trait's reach is Reach.Authority, so only the room holds it. Move the read to a system whose entry leaves runsOn out, which runs on the room alone. Where the page needs the value too, give the trait a reach the room streams, with predicted: true where the player's page predicts it on the character, or reach: Reach.Local so the room and the page each keep their own.The check covers a system declared RunContext.Both or RunContext.Client, and a predicted system, through query, queryFirst, get, has, set and add on the world and on an entity, and through the engine’s updateEach. It runs where the world is a dev world: the development page, a headless game and a test. A built game carries no check. A game with no room holds every trait itself, so nothing is refused there. Outside a system, the dump and the devtools read every trait as before.
To fix the error, take the first of the following that fits:
- The rule belongs to the room. Move the read to a system whose entry leaves
runsOnout. - The page needs the value. Give the trait a reach the room streams, such as
Reach.Everyone. - The player’s page predicts the value on the character. Define the trait with
predicted: true, as Predicted systems describes. - The room and the page each work the value out, and nothing rolls it back. Define the trait with
reach: Reach.Local, as Choose who a trait reaches describes.
The check knows a trait made with defineTrait. A trait made with the engine’s unnamed trait has no name and no options, so the check cannot tell who holds it.
Predicted systems
Section titled “Predicted systems”In a multiplayer game, mark each system that steps a player’s character as a predicted system: set predicted: true on its entry in the plugin. The engine runs a predicted system on one kind of step besides the world’s: a replay. When the room corrects where the player’s page has the character, the page runs the player’s latest moves again from the corrected spot. The room steps every character once on each of its ticks, on the player’s input for the tick or, where it has none, on the player’s last input and then a still one, so a character’s steps and the world’s are the same steps on the room.
The room and the player’s page both step the character, so a predicted system runs on both and declares no runsOn. definePlugin refuses predicted: true beside RunContext.Server or RunContext.Client.
On a replay, only the predicted systems run, in the order the step runs them, each once a tick over the entities step.rerunEntities names: everything the player’s page predicts, the character and any kart or pet the player controls predicted. An unmarked system runs once on each of the world’s steps and never on a replay. A single-player game has no room, so it never replays, and the mark changes nothing there.
To tell the two kinds apart, ask which clock the system runs on:
- A dash’s charges are a predicted system’s. It recharges them as the character moves. Left unmarked, it would not run on the player’s page’s replay, so the player’s page would replay the player’s steps without the recharge and refuse a dash the room ran, and the room would correct the character again.
- A monster’s AI is not. It steps the monster once per world step. Marked, it would run again on every replay on a page that predicts it, and the monster would move faster there whenever the room corrects the character. The
regeneration.healsystem in the plugin above runs on the world’s clock too, and leavespredictedout.
A predicted system follows these rules:
- Walk the characters with
step.updateEachPredicted(query, callback), which hands the callback each character the step may touch that the query matches. The callback receives the query’s traits and the character as aPredictedEntity, whose predicted traits it may write. The set is every character on the room and in a game played alone, the player’s own predicted set alone on the player’s page, and on a replay the setstep.rerunEntitiesnames. The pass uses one order on every world, bases before riders. It never hands over an entity no player controls. In a dev world, the engine prints a warning naming a predicted system that moves an entity outside the set on a replay, as one that walksanyEntitytraits withupdateEachcan. It is the one pass that writes a predicted trait of yours. - Keep the system’s state for a character in a trait declared
predicted. The player’s page keeps every predicted trait of the character for each step, and when the room’s value differs, it restores every one of them to the room’s exact value and replays the steps since. A timer in a predicted trait is where the room had it after the replay, so the replay counts it down again from there. A timer in any other trait is not restored, so the replay counts it down a second time. Keep no state for a character in a module variable or a closure either: the replay never restores it, and no check names it. - Draw a number both ends predict with
step.random(character), the same on the room and the player’s page for one tick and character. Draw a hidden roll, such as loot, or read the clock only wherestep.authoritativeis true, so the room alone draws it and the player’s page takes the result. In a room in development, the prediction checks name a predicted system that callsMath.random,randomorDate.nowthere, or that writes a trait of the character it does not predict. - Leave a character’s predicted traits to the predicted systems. The type holds it for a trait declared
predicted: true: only thePredictedEntitya predicted system is handed writes it, and a one-off change the room makes goes throughgrantPredicted, as When the room changes the player’s character shows. For ananyEntitytrait, in every dev world, the room’s and a headless game’s among them, the prediction checks name a game’s system that is not a predicted system as it writes one.
Type the function as a PredictedSystem, whose step is a PredictedStep. TypeScript then refuses it in an entry that leaves out predicted: true.
The following plugin recharges a dash’s charges as a predicted system, in the rules phase, where a timer counts. The dash itself is a push: its command’s reader calls pushCharacter, which holds the character’s velocity for the dash’s length, as Change the character’s movement describes. Never write the character’s velocity yourself: the engine’s steer sets it from the input on every tick.
import type { World } from "@spawnite/engine/core";import { addTrait, createQuery, definePlugin, defineTrait, type PredictedStep, defineSystem, Phase,} from "@spawnite/engine/core";
/** A character's dash charges, and the seconds toward the next: predicted, so * the player's page counts them as the room does and rolls them back * with the character. */const ChargesTrait = defineTrait( "charges", { charges: 2, recharge: 0 }, { predicted: true },);const chargers = createQuery(ChargesTrait);
/** Brings a charge back every three seconds, up to two. */function rechargeDashes(step: PredictedStep) { step.updateEachPredicted(chargers, ([state]) => { if (state.charges >= 2) return; state.recharge += step.deltaSeconds; if (state.recharge < 3) return; state.charges += 1; state.recharge = 0; });}
/** A dash's charges for each character. */export const dash = definePlugin(() => ({ name: "dash", description: "A dash's charges for each character.", onCharacterSpawn: ({ writer, character }) => { addTrait(writer, character, ChargesTrait); }, systems: [ defineSystem({ name: "rechargeDashes", phase: Phase.Rules, description: "Brings a dash charge back every three seconds.", predicted: true, run: rechargeDashes, }), ],}));The step’s profile and the devtools name the system dash.rechargeDashes.
A predicted command reaches the predicted system that answers it on its tick: readCommands(step, handle) yields the tick’s commands, each with entity, a PredictedEntity, payload, tick, accept and refuse. The player’s page keeps each command and hands it to every replay of the tick the room ran it on, so a dash started by a command replays with the command, and one the room refused replays on no tick. Build a predicted mechanic describes how the room settles each one.
A predicted system keeps its state in a predicted trait, and a replay restores that trait before it runs the system again, so the system never asks whether a step is a replay. A re-run’s step.rerunEntities names the player’s set; it happens in the player’s page’s replay after a correction. The multiplayer page says what a predicted trait is and how it travels.
The time of day
Section titled “The time of day”A system reads the date with readUnixSeconds(step): Unix seconds at the tick, the same value on the room, on the player’s page, in a correction’s re-run and in a replay. A hook reads it through the step it receives, and a view or a save’s read and restore through the world, readUnixSeconds(world). Never Date.now(), new Date() or performance.now() in gameplay: each reads a different time on every end.
Each tick moves the stamp by one tick’s seconds, which is 1/30 s at a room game’s default of 30 ticks a second and 1/60 s at 60 ticks. Where the room’s wall clock runs more than a second ahead of it, as after a suspend or a stall, it jumps forward to the wall as the step ends, and it never steps back. The step’s deltaSeconds is the simulation’s time, one tick, jumps aside; the real time that passed, a jump included, is the difference of two stamps. Time while the game is closed shows a crop that ripens in real time and a market that restocks each day.
The game lint refuses the wall clock and the machine’s local time inside gameplay. Gameplay is a function written in a define* call’s options, such as defineSystem’s run or defineSave’s restore, and a function typed as a system or taking a step. The system types are System, AuthoritativeSystem and PredictedSystem; the step types are SystemStep, AuthoritativeStep, ClientStep, PredictedStep and UnpredictedStep. A helper those call is beyond its reach: pass it the stamp, as the samples pass now, and spawnite replay check finds what slips through.
A timer of a game’s own
Section titled “A timer of a game’s own”A timer a game keeps, such as a buff’s length, a door’s hold or a round’s countdown, keeps the tick it ends on rather than seconds it counts down. readTickAfterSeconds(step, seconds) returns that tick, and any span above zero ends at least one step on. readSecondsUntil(step, tick) reads the seconds left, and zero once the tick is reached. readSecondsSince(step, tick) reads the seconds since a tick, such as the tick a creature entered a mode. A view reads each through the world, as readSecondsUntil(world, tick).
The trait is then written as the timer starts and as it ends, and on no step between, so a room sends it twice and a quiet room sends nothing but its heartbeat. A trait written every step, such as one that counts its seconds down, sends a change every step to every page that sees it. The poison above keeps the tick it ends on and the tick its next damage lands on, so it is written at a hit and once a second. A timer of N steps started on tick T runs on ticks T to T + N - 1, so step.tick >= endTick ends it. A tick means something only in the room that counted it: a save keeps seconds, never a tick.
Photon Fusion’s TickTimer keeps the tick it ends on the same way, and the engine’s cooldowns, casts, respawns, machine waits and day clock all do.
The player’s input
Section titled “The player’s input”On a page and in a game played alone, the step carries the player’s input as input, a StepInput: one tick of every input the game’s plugins declare. Where the game lists characters(), these include the character’s move, heading and jump, each at its place in the composition. A room’s own step carries no input, because each player’s character holds what that player’s page last sent. A system reads a value by its handle, never by its place.
Which system reads the input depends on what the player drives:
- A controlled entity that is no character, such as a car on a track: the step copies the character’s move into each track mover the player steers,
steerfrom its x andthrottlefrom its y. A system reads them off the mover, as the TrackMover’s throttle does. - A player’s character: a predicted system reads the character it steps, with
readInput(character, plugin.inputs.name), for a key the game declares in its plugin’sinputs. A room then steps each character on its own player’s keys, as Hold a key describes.
Events
Section titled “Events”A system reads what happened, such as a hit or a death, with readEvents(step, DamagedEvent): every event once, from where it last read. It emits its own with emitEvent. Events says how an event is read, heard, streamed and defined. Hearing it in a view says which events a view that mounts for a new entity hears.
State a continue can carry
Section titled “State a continue can carry”A dev room keeps a checkpoint of its world, and a continue writes it back into a fresh room to run a moment again. The checkpoint holds every trait of every entity, the world’s own traits, the physics world and the world’s random stream, so keep a system’s state in those places:
-
Keep a system’s state in a trait. A count, a timer or a list a system keeps in a variable of its module, or in a closure it made, starts afresh in a continue, which then parts from the room. Put it in a trait, on an entity or on the world, written as Writing a trait says. A scratch vector written before each read is safe.
-
Draw from the world’s stream.
random(step)draws from 0 up to 1, on the room’s step or the authorityuseAuthorityEffecthands a logic component.randomRangedraws between two numbers, andrandomInta whole number between two, both included, as Godot’srandi_rangeand Roblox’sNextIntegerdo.shuffleshuffles a list in place, as Godot’sArray.shuffledoes.The stream’s state is the world’s
WorldRandomTraittrait, so a continue draws what the room drew. Every world starts from the same seed, as a test’s world should, and a room draws a fresh seed withMath.randomas it starts, so no two runs play alike.seedRandomstarts it from a seed of your own, as Unity’sRandom.InitStatedoes.Math.randomstays fine for what only the page draws, a spark’s scatter or a sound’s pitch. -
Use the step for time. The time of day names the date read and the per-tick duration.
A game’s lint warns on Math.random, and on a variable of the module a system writes, in any function that takes the world or is typed System. spawnite replay check proves the rest: it names the first trait where a continue parts from the room.