Routines
routines() builds what an NPC does: a set of named routines, each a list of steps, and the events that start one. It compiles to a state machine: a routine is a compound state, each step a state inside it, and resume a deep history state. The machine declares tags: false, since a tag for each routine and step of every kind of NPC would slow the dump, so the routine system reads the step from the machine’s record. Unreal splits an NPC the same way, with StateTree deciding and the controller moving: the machine decides, and the routine system writes the NPC’s path as a click writes the player’s.
import { NpcEvent, route, routines } from "@spawnite/engine";
const market = route({ stall: [4, 0, -2], well: [8, 0, -6], herbs: [3, 0, -9],});const bench = route({ bench: [2, 0, -3] });
const mira = routines("mira") .routine("morning", (r) => r .walk(market, { pause: { well: 4 } }) .wait(3) .then("rest"), ) .routine("rest", (r) => r .walk(bench) .wait({ between: [20, 40] }) .say("*yawns*") .then("morning"), ) .routine("greet", (r) => r.face().play("jump").say("Hello!").resume()) .on(NpcEvent.Approached, "greet") .start("morning");Its name
Section titled “Its name”routines("mira") names the routines, and the machine is named for the name, miraRoutines: its trait dumps, streams and checkpoints under it. toMachineId(name, kind) makes that id, for a kit that builds machines of its own kind. Every NPC handed one build runs one machine, so a crowd of guards shares routines("guard") by intent, and two NPCs with one name over their heads and routines of their own each keep their own machine. A second build under a name, as a hot reload makes, takes the name over, so give each set of routines a name of its own. A name holds at least one letter or digit, and two names make two machines only when their letters and digits differ: routines("north-guard") after routines("north guard") throws, naming both. Unity’s Animator Controller, Unreal’s Behavior Tree and Godot’s resources work the same way: the named asset holds the logic, and every character that references it runs it.
walk(route, { repeat, yoyo, pause }): walks the route once, and the step ends at its last point, so the routine goes on to its next step.repeatis how many more passes follow the first, 0 by default;Infinitywalks the route until an event starts another routine.yoyowalks every second pass back down the points, so{ repeat: 1, yoyo: true }walks out and back.pauseis seconds at every point, or, on aroute(), seconds at each point by its name.walkToTarget({ reach, repathDistance, face }): walks to a target a game’s system sets at run time, such as the ripest tree, as Walk to a target says.wait(seconds)orwait({ between: [min, max] }): counted by the fixed step, as any machine’s wait. A roll between two numbers is drawn from the world’s seeded random each time the wait begins, so two NPCs from one set of routines wait different lengths, and a replay waits as the run did. The roll sits on the machine’s trait, so a checkpoint keeps it and a wait an event interrupts resumes with it.play(clip, { seconds }): a clip the avatar has, which the view crossfades to forseconds, 2 by default, and back, as it crossfades a change of pose. The room never loads a model’s file, so it cannot read a clip’s own length as Unity’s Animator does: give a clip of another length itsseconds. The avatars play their poses’ clips:idle,run,turnLeft,turnRight,jump,runJumpandland. A clip it lacks is skipped, and a dev world warns once naming it. An NPC that wears a model plays the model’s clip for the pose, or any clip of the model’s file by the file’s own name, such asplay("interact"); the room never loads the file, so a page warns once where the file lacks the clip.say(line): a line right over its name for four seconds; the routine goes on at once. The line wraps when long and fades as the camera draws away. For a conversation with one player, give the NPC a Dialog.turn(degrees),face(point)andface(): a turn on the spot, left for a positive number, or a turn toward a point,[x, z]or[x, y, z]by its x and z, as Unity’sLookAtturns toward a position.face()turns toward the nearest player’s character, the one who came close or pressed the prompt. A point where the NPC stands keeps its facing. The NPC turns at its movement’sstandTurnRate, for at mostmaxTurnSeconds, so a quarter turn takes under three tenths of a second by default, and the routine goes on at once while it turns. A turn goes the short way round, soturn(270)turns right by 90°, and aturnwhile one is under way adds to where that one ends.do(name, data): a step the game’s own system answers, such as ringing a bell or handing over a key. It emitsRoutineActionRequestedEventon the NPC with{ name, data },dataan empty string when left out, and the routine goes on at once. The dump’seventslists it asroutineActionRequested.then(name),resume(), or nothing: go to a routine, go back to the routine an event interrupted at the step it was on, or repeat this one. A routine an event starts that names neither ends inresume().resume()fits only a routine an event starts, andstartrefuses it on any other, naming the routine.
A walk takes the shape of Phaser’s PathFollower and GSAP’s tweens, repeat: 0 with yoyo, because a walk is one step in a sequence: it ends so that the next step can run. Unreal’s and Roblox’s MoveTo also move once and report arrival.
Walk to a target
Section titled “Walk to a target”walkToTarget() walks to the target in the NPC’s WalkTargetTrait, which a game’s system writes with setWalkTarget(step, npc, target): an entity, a point [x, z] on the ground or [x, y, z], or null for none. Unreal’s Move To task reads a blackboard key the same way, and Unity’s SetDestination and Roblox’s MoveTo take a point or a part. The system may set it before the step, or while the step runs. The trait is the NPC’s own on each side, so a dump shows it and set_trait sets it.
- With no target, or once its entity is destroyed, the NPC stands where it is and waits for one. A routine of
.do("choose-tree").walkToTarget()works: the system answers thedoon its next run, and the walk sets off then. - The walk ends once the NPC stands within
reachmetres of the target, measured on the ground, and never nearer than the walk’s own arrival radius, as Unity’sstoppingDistanceand Unreal’sAcceptableRadius.reachis 0 by default. Where the navmesh reaches no nearer, as for a target on the ground’s edge, the walk also ends within 1 + √2 arrival radii, since the bake stops the navmesh a body’s radius short of the edge.face: trueturns the NPC toward the target as it arrives. The step clears the target as it ends, so the next pass walks to the target the system sets anew. - It follows the target: the walk sets off again once the target stands more than
repathDistancemetres, 1 by default, from where the walk last set off for, and whenever its path runs out short of the target, as a conversation clears it.
It gives up, as Fences says, past its timeout, on a target walkTo refuses, where it stops short of the target because the navmesh reaches no nearer, and on a target past the NPC’s leash. A give-up clears the target, so a routine that answers NpcEvent.Stuck and resumes comes back to a step with no target, and the NPC stands until one is set: set the next one in the handler, such as with .do("choose-tree") before resume(). An NPC pushed past its own leash walks home, then on to its target. One routine names one target at a time: a game with a work target and a delivery target writes each before the step that walks to it. A height check for stacked floors, and an offset from an entity, are left out: give the point instead.
Routes
Section titled “Routes”A walk takes a route in one of three forms:
route({ stall: [3, 0, -2], well: [8, 0, -6] })names its points in the order the walk visits them, so apausecan name the well. A point is[x, y, z], or[x, z]standing on the ground. Name each point with a word: an object puts a number-like key first, soroute()refuses one."meadowToRollingField", the name of a path the map holds under itspaths, walked point to point with the ground giving each point’s height. Its points have no names, sopausetakes seconds for every point.- A list of points,
[[4, -2], [8, -6]], withpausein seconds for every point.
The types keep a pause by name to a route() and its names. A map path the map does not hold, or a paused point the route does not name, skips the walk, and a dev world warns once naming the NPC, the routine and the name.
Events
Section titled “Events”on(event, name) on the builder starts the routine name on the event from any routine an event did not start. Inside a routine it fires only there. NpcEvent.Approached fires when a player’s character comes within the NPC’s Interact radius, NpcEvent.Interacted when one presses its prompt, and NpcEvent.Stuck when a walk gives up on a point, as the fences below describe. An event routine takes no event, so a second event while it runs is dropped, and Approached fires again once the character leaves and comes back. A walk an event interrupts stops where the NPC stands and keeps its place on the route for a resume, a clip an event interrupts gives way to the pose, and a wait keeps the seconds it had counted.
on also takes a game’s own event name, such as "ALARM". A game’s system sends it through the routines’ machine, compileRoutines(guard).machine.send(step, npc, "ALARM"), where guard is what routines() built. The names DONE and ARRIVED end a step inside every routine, so on refuses them.
While a player holds a conversation with the NPC, the NPC holds the TalkingTrait trait and its routine holds: the NPC stops, faces the player, and takes no event, while every other machine on it runs on. Once its last conversation ends, the trait comes off and the routine goes on at the step it was on: a walk heads back for the point it was walking to, and a wait keeps its seconds. A game holds the NPC itself with MachinePausedTrait, as Unity’s isStopped and Unreal’s PauseMove do: every machine on it holds, its routine’s timers with them. It stands on the path it was walking until the game takes the trait off, then walks on along the same leg. A chase is not held. A player’s character keeps its own input. In a room that culls by interest, the routine holds the same way while the NPC is suspended because no player is near, as the NPC page says.
Fences
Section titled “Fences”Four fences keep an NPC in the world:
- The navmesh is the world’s edge. A walk gives up on a route point
walkTorefuses, and on one it stops short of, and a dev world warns once naming the NPC, the routine and the point. - The
leashon the NPC, from its spawn. - A timeout per point: the distance over the walking speed, twice, plus 2 s, as Roblox’s
MoveTogives up after 8 s. On a timeout the NPC is markedStuckTrait, the walk gives up on the point, and a dev world warns once. - Every routine is finite: the builder makes lists, and
thenandresumeare the only jumps.startrefuses a routine name nobody declared, and aresume()in a routine no event starts.
A walk that gives up on a point sends the routine NpcEvent.Stuck, and emits the GaveUpEvent event. The dump’s events lists it as gaveUp with { point, reason }: the point’s place in the route from 0, or 0 for a walk to a target, and a GiveUpReason. The reason is timeout, no-route for a point walkTo refused, partial for one the NPC stopped short of, or past-leash for a target past the leash.
A point across a gap the navmesh has no route over, such as a dock a wall cuts from a deck, is not refused: the NPC walks as near as the navmesh reaches, as Unity’s and Unreal’s agents walk a partial path, and gives up with partial where it stops. A game’s system that must tell a short end from an arrival reads the GaveUpEvent and its reason, GiveUpReason.Partial. A point on the ground’s edge counts as reached, though the navmesh stops a body’s radius short of it. The check is made on the ground, so a point on a floor straight overhead, or behind a wall thinner than a body, reads as reached. A walk whose path keeps emptying short of its point still gives up on its timeout. With no .on() for the give-up, a dev world warns once, naming the NPC.
A routine answers a give-up with .on(NpcEvent.Stuck, "lost"), and a resume() in lost heads for the next point, where a then back to the walk’s routine starts the walk over. With no .on() for it, the walk goes on to the next point, and past the last one the step ends; a walk to a target ends at once. Roblox’s MoveToFinished reports reached as false the same way. Unreal’s path following ends with Blocked or Aborted where a move fails, but with Success at a partial path’s end, leaving HasPartialPath() to tell the two apart, as the reason does here.
import { NpcEvent, routines } from "@spawnite/engine";
const guard = routines("guard") .routine("round", (r) => r.walk("gateToTower", { repeat: Infinity })) .routine("lost", (r) => r.say("Hm, blocked.").resume()) .on(NpcEvent.Stuck, "lost") .start("round");In words
Section titled “In words”describeRoutines gives each routine as a line, such as morning: walk stall to well to herbs, wait 3 s, then rest, which the devtools’ Wiki tab lists under the NPC.