Npc
<Npc> spawns a non-player character inside a Landscape: the same walker, body, avatar, clips and navmesh path as the player’s character, driven by its routines instead of a person. World of Warcraft makes an NPC the same way, as data: a name, a title, a level, a faction, and a path with a pause at each point. An NPC with no routines stands and plays idle. To send an NPC to a station a player chose, such as a worker to a tapped tree, give it an order. An avatar is posed less often while it is small on screen or out of view, as another player’s character is, unless cullingMode says otherwise; a model is posed every frame.
import { Faction, Interact, Npc, NpcEvent, routines } from "@spawnite/engine";
const guard = routines("guard") .routine("post", (r) => r.wait({ between: [10, 20] }).turn(90)) .start("post");
export function Guard() { return ( <Npc name="Bram" title="Gate guard" level={8} faction={Faction.Neutral} position={[2, 0, 4]} routines={guard} > <Interact prompt="Talk" /> </Npc> );}It takes <CharacterSpawn>’s body fields, its look, position and facing, and these of its own:
nameandtitle: drawn over its head in Text’s white with a dark edge, the title under the name as WoW draws a subname. The AI tree names it by them and its faction: “Mira, a herbalist, friendly”.nameplate:falsedraws no name or title over its head, for a figure that dresses a scene, as Roblox’sDisplayDistanceType.Nonehides a humanoid’s. The AI tree still names it, and a line it says still shows.base: what floats under it, such as a boat the NPC works on: a map prop’s id, or a handledefineIdleMotiondeclares. Its drawing rides the deck under its feet, as IdleMotion says, while its body stays where it stands.level: a number a game reads.faction:Faction.Friendly,NeutralorHostile, friendly by default. It says which side the NPC is on, and does not make it a target: an ability strikes an NPC that carriesTargetableTrait, which Targeting shows how to give it.routines: whatroutines()built.unseen: what it does while no player is near, in a room that culls by interest:Unseen.Suspendby default, as When no player is near says.movement: its movement settings laid over the defaults, as aCharacterSpawn’s:{ speed: 1.4 }walks where the default 5 m/s runs, as Unity’sNavMeshAgent.speedand Roblox’sWalkSpeedset it.movementMode: how it moves while it needs no physics:NpcMovementMode.NavWalkingalong the navmesh by default, orNpcMovementMode.Walkingthrough the character controller every tick, as How it moves says.leash: metres from its spawn it may walk. A route point past the leash is skipped with a warning at spawn, and a walk that carries it past the leash ends and walks it home, as WoW’s evade does. A routed NPC has none by default, since its route bounds it.
Its children are behaviours on it, as on an Entity. <Interact prompt="Talk" /> shows the prompt when a player’s character comes close and emits the InteractedEvent event on a press, which a routine answers with NpcEvent.Interacted. <Dialog tree={...} /> gives it a conversation, which a press of that prompt starts for the player who pressed. While any conversation goes on, the NPC holds the TalkingTrait trait, which holds its routine alone.
What it wears
Section titled “What it wears”An NPC wears one look, from the same props the player’s character takes:
avatar: a nameregisterAvatarregistered.model: the name of a model the game registered, such as the example template’svisor-bot. Where its file has clips, it plays the ones its pose asks for,idleat rest,walkandrunblended by its speed, andjumpoff the ground. The model’s registration names the file’s own clip for each that the file names another way, withclipssuch as{ run: "Sprint" }. ItsclipSpeedsgives the ground speed at which its walk and its run play at their own pace, as the player’s model does. A routine’splaystep names one of the poses’ clips, as Routines lists them. A model plays its clip for that pose, through its registration’sclips, or else the file’s clip of that name, such asland; a model with neither plays nothing over its pose, and a dev world warns once. A clip under any other name, such as a wave, plays withplayClip, as on the player’s model.shapeandcolor: a primitive in a colour, the capsule when it names no look.
Two looks at once fail the typecheck, such as an avatar beside a model, or a color beside either: a color tints the primitive alone. This merchant wears the robot the player wears, and walks where it would run:
import { Faction, Interact, Npc, type ModelRegistration,} from "@spawnite/engine";
/** The robot the player wears, registered as `visor-bot`: its file's walk * plays where it would run, on every character that wears it. */export const visorBot: ModelRegistration = { path: "/assets/visor-bot.glb", clips: { run: "walk" },};
/** The lobby's merchant, in the robot the player wears, which walks where * it would run. */export function Merchant() { return ( <Npc name="Tobin" title="Merchant" faction={Faction.Friendly} position={[4, 0, -3]} model="visor-bot" > <Interact prompt="Talk" /> </Npc> );}What it holds
Section titled “What it holds”Its npc trait holds its name, title, level and faction, and what its routine is doing: the routine and the step, the seconds on the step, the route point it walks to and the pass along the route it is on, and the line a say step gave it. That line draws right over its name, wrapped and faded with the camera’s distance. Its routines compile to a state machine whose trait dumps beside it under the name routines() took, miraRoutines for routines("mira"). A spawnite play dump shows both each step, so a test asserts where it is and what it is doing.
In the devtools
Section titled “In the devtools”The tree shows each NPC as a row under its name, and the Map tab counts it under the avatar it wears, by its registered name, where it wears one. The inspector shows its npc trait and its machine’s card: the routine, the step in words, such as walk stall to well to herbs, the machine’s state and a wait’s seconds left. The Wiki tab lists each NPC under the npc kind with its routines in words and, where it has a Dialog, its lines by node with the choices each offers. A conversation’s machine shows in the Wiki tab under machine, as any machine does.
In a room
Section titled “In a room”The room spawns and steps an NPC, and each page draws the one the room streams at its place in the scene, as it does an Entity, in the appearance the room streams, so its model draws on every page. spawnNpc takes the same avatar, model, shape and color for an NPC a system spawns, and the game’s own character view draws NPCs too. An NPC a scene places with <Npc> keeps its name over its head whatever the view draws, unless its nameplate is off; one spawnNpc spawns shows no name of the engine’s.
The routine system runs on the server, as Chase does, and a single-player game runs it on the page. A player’s press of its prompt reaches the room as Interact describes, and the stream carries its npc trait and its machine’s trait to every page, so each page draws the same line over its head. The room runs each conversation too, and streams its record to the talking player alone, as Dialog describes. routines() compiles its machine as start() ends the build, so a module that builds it at its top registers the machine’s name on every page before the stream brings its trait, even while a Landscape waits on its map. The page’s inspector and Wiki tab show the routines in words as the room’s do.
How it moves
Section titled “How it moves”An NPC walks along the world’s navmesh by default, as Unreal’s NavWalking moves a character. Each tick it steps along the navmesh’s surface toward where its path or its chase takes it, stands on the ground’s own height there, and keeps out of the characters beside it, with no sweep of its capsule. It costs the room a fraction of what a player’s character costs, and a player sees it walk where the character controller would walk it: on the ground exactly, and within the navmesh’s 10 cm cell height on a crate’s top.
A new NPC stands on the first thing under its spawn point: a voxel grid’s top, a placed floor, a prop with a collider, or the terrain where nothing else is there. A dynamic body is not such a thing: no character stands on one, so a point over a crate or a ball stands on the floor under it. A point under the terrain is lifted onto it, and a point up to a capsule’s height inside a floor stands on the floor’s top. A teleport differs: it puts a character at its point exactly and lets it fall, since a game that teleports means that point.
Where nothing lies under the point, as past the ground’s edge, or where its capsule stands inside a collider there, the engine builds the NPC no body. It stands where it was put, NpcSpawnTrait holds the NpcSpawnRefusal that says why, and a development world warns. The engine tries again each tick, so the NPC stands once the collider goes. A player’s character finds its floor the same way, but it is always built, since it must have a body: StuckTrait and freeCharacter take it from there.
On any tick it needs physics, the character controller moves it, as it moves a player’s character:
- It has not moved yet, and settles on its floor.
- It stands in the air, or a push, a shove or a launch acts on it.
- It stands on a body that moves or on another character, carries
StuckTrait, or crouches. - Its step meets a dynamic body, a character the navmesh cannot part it from, or a collider that changed and whose navmesh tiles have not rebaked, as Chase says.
- No navmesh lies under it, its step leaves the navmesh over a drop, or the navmesh’s edge holds a step of its route at a corner.
It walks the navmesh again on the first tick none holds. NavMeshMoveTrait holds why its last move went through the controller, null while it walks the navmesh: the inspector shows it, and a spawnite play dump carries it.
movementMode: NpcMovementMode.Walking moves it through the controller every tick, for an NPC that must always have physics, such as one that rides a conveyor or shoves crates aside. It goes on definePrefab, on spawn, on <Entity> and on <Npc>, and setTrait on NpcMovementModeTrait changes it at run time. An NPC wider or taller than a player’s character, or whose controller steps lower, also moves through the controller every tick, since the navmesh was baked for that character.
A game’s own movement moves an NPC the same way: moveAlongNavMesh(step, npc, { velocity }) answers a refusal where it did not move it, and the game then moves it with moveCharacter.
When no player is near
Section titled “When no player is near”In a room that culls by interest, the room’s CPU follows the NPCs players can see. An NPC no page wants, outside every player’s interest, costs the room little or nothing, and unseen says how:
Unseen.Suspend, the default for every NPC but a chaser: it stands where it is. The engine moves it by no path, steers it toward no target, and holds its routine and the routine’s waits. Countdowns, such as a cooldown or a respawn, still end on time.Unseen.Throttle, the default for a chaser: it moves on one tick in four, as far as the four ticks take it, along the navmesh. Its chase and its routine run every tick, so a hunter keeps closing in and a merchant keeps to its schedule.Unseen.Simulate: every tick, as while a player watches, for an NPC whose every step matters unseen.
unseen goes on definePrefab, on spawn, on <Entity> and on <Npc>, and setTrait on UnseenTrait changes it at run time. A player who watches an NPC sees it move exactly as without culling. With culling off, and in a game played alone, every NPC simulates.
A game holds an NPC where it stands for its own reason, culling or none, with MachinePausedTrait: its routine and its walk hold until the game takes the trait off, as Routines says.
A wolf pack, where an ordinary wolf stops when no player is near, the alpha keeps hunting, and the game’s own howl leaves the stopped wolves out:
import { ChaseTrait, createQuery, defineGame, definePlugin, definePrefab, defineRoom, defineSystem, defineTrait, editTrait, Not, Phase, readEach, SuspendedTrait, Unseen, type AuthoritativeStep,} from "@spawnite/engine/core";import { behaviours } from "@spawnite/engine/behaviours";import { characters } from "@spawnite/engine/characters";
// A wolf pack in a world that culls at 40 m. A wolf no player is near// stops where it stands and costs the room nothing; the alpha keeps// hunting at a quarter of the cost, so it closes in from anywhere. The// pack's own howl, a system of the game's, leaves the stopped wolves out.
export const room = defineRoom({ maxPlayers: 20, interest: { radius: 40 } });
/** How many times a wolf howled. */export const HowlTrait = defineTrait("packHowl", { howls: 0 });
export const wolf = definePrefab("packWolf", { traits: [ChaseTrait({ speed: 3, reach: 1 }), HowlTrait], // A chaser throttles by default; a wolf of the pack stops instead. unseen: Unseen.Suspend,});
export const alpha = definePrefab("packAlpha", { traits: [ChaseTrait({ speed: 4, reach: 1 }), HowlTrait], unseen: Unseen.Throttle,});
const howling = createQuery(HowlTrait, Not(SuspendedTrait));
/** Every wolf that is not suspended howls once a second. */function howl(step: AuthoritativeStep) { if (step.tick % 60 !== 0) return; readEach(step.world, howling, (_traits, wolf) => { editTrait(step, wolf, HowlTrait).howls++; });}
export const pack = definePlugin(() => ({ name: "pack", description: "Howls with each wolf of the pack that is not suspended.", requires: [characters, behaviours], systems: [defineSystem({ name: "howl", phase: Phase.Rules, run: howl })],}));
export const game = defineGame({ name: "pack", start: "hills", plugins: [characters(), behaviours(), pack()], room,});- No page draws a stopped NPC. An NPC simulates while any page wants it. One a page starts to want simulates for a tick before that page receives it, so it arrives standing on its floor. After a teleport, an NPC that was suspended appears one send later than the rest.
- It still needs physics when pushed. A knockback, a fall or a moving lift under it keeps an unseen NPC simulating, through the controller, as How it moves says.
- A hit still lands. A suspended NPC keeps its collider, so a projectile or a ray hits it, and it takes damage and dies as usual.
- A throttled NPC moves in steps. It moves on its own ticks, so its path’s corners and the triggers it walks through are read there, and it may cross a thin trigger unseen. Its chase checks reach every tick. Two throttled NPCs may pass through each other.
- A path written to a suspended NPC waits.
walkToon one warns once in development, and the NPC walks it when a page nears it. Give itUnseen.Throttleto keep it walking. - Your own systems read the same.
SuspendedTraitmarks a suspended NPC, andThrottledTraita throttled one with the ticks its move covers. Leave suspended NPCs out of a costly query withNot(SuspendedTrait), and listSuspendedTraitin a machine’sheldByto hold it, as the routines do.
Rust suspends its AI far from players by default, and Minecraft stops the entities outside its simulation distance. Unreal’s Mass ticks far agents less often. Unity, Godot and Roblox leave it to the game’s own code.