Appearance
NPCs
NPCs are the objects that live in a level: signs, shopkeepers, doors, wandering townsfolk, chests. Unlike weapons, which belong to a player and follow them around, an NPC belongs to a level and is seen by everyone standing in it.
Every NPC can carry two scripts:
| Half | Runs on | this is | Writes go to |
|---|---|---|---|
| Serverside | the server, once | NpcThis (server) | everyone in the level (server-authoritative) |
| Clientside | every client in the level, separately | NpcThis (client) | this client only (never sent anywhere) |
Put game logic — who can open the door, what the shop sells, where the NPC walks — in the serverside half. Use the clientside half for things only one player should see or that react to local input: a light glow, a hover hint, a key press that asks the server to do something.
Where NPC scripts live
Level NPCs are baked into the level file (.glvl), scripts included. You create and edit them in GRC's level editor:
- Open the level, pick the NPC tool and right-click to place a new NPC at the cursor tile.
- Double-click the NPC to open its editor: image, X/Y (tiles) and two script tabs, Clientside and Serverside. Each tab has full IntelliSense for its side.
- Save the dialog (Ctrl+S), then save the level. Saving the level uploads it and hot-reloads every NPC in it (see Hot reload).
Both halves are ordinary TypeScript modules: export is optional (every top-level function is a handler), they can join classes and import shared lib modules. The serverside half sees the server globals (echo, triggerClient, flags, timers, …) plus npc.server.d.ts; the clientside half sees the client globals (player is still the local player, findimg, keydown, …) plus npc.client.d.ts.
The serverside half can't use await at the top level (outside a function), because the server runs one copy per level and instance from the same compiled code. A script that does fails to compile: the server log shows the error, and the NPC runs without its serverside half. Do async work in onCreated instead: async function onCreated() { await sleep(1); … }.
Keep level scripts tiny
Because the source is inside the level file, the same behaviour copied into twenty NPCs is twenty copies to maintain. Put the behaviour in a class and let each NPC only set its configuration and this.join('name') — see Tutorial 5.
Lifecycle
A level's NPCs are instantiated the first time a player enters the level (for a gmap, when the member level first comes into a player's view). A level nobody has visited has no running NPCs. Once activated, its serverside NPCs keep running — onUpdate and timers included — whether or not anyone is still in the level, like in Graal.
Clientside halves are created when the NPC appears on a client (you entered the level) and unloaded when you leave it.
Events
Handlers are exported functions; this is the NPC. Use function declarations, not arrow functions, for handlers (arrow functions inside a handler are fine and keep this).
Serverside
| Handler | Fires when |
|---|---|
onCreated() | The NPC was instantiated (level activated) or the level file was updated. |
onPlayerEnters(player) | A Player entered the NPC's level (again after a hot reload). |
onPlayerChats(player, chat) | A player in the level typed chat. Script-set chat doesn't fire it. |
onUpdate(dt) | Every server tick (20 per second); dt in seconds. |
onAction<Name>(player, ...params) | A clientside triggerAction hit this NPC's shape. |
onAction<Name>(...params) | A serverside this.level.triggerAction hit it (no player argument). |
onShot(data) / onShotAt(x, y, data) | Projectiles — see Projectiles. |
onMovementFinished() | A this.move() with option 8 ended. |
Clientside
| Handler | Fires when |
|---|---|
onCreated() | The NPC appeared on this client (level entered, or hot reload). |
onPlayerEnters(player) | A player entered — the local player too, right after onCreated. Receives a ChatPlayer. |
onPlayerChats(player, chat) | A player chatted. /-commands arrive here too. |
onUpdate(dt) | Every frame. |
onKeyPressed(key) | A key went down (once per press), same key names as weapons. |
onAction<Name>(...params) | A serverside level.triggerAction hit this NPC. |
onPMReceived(sender) | A PM arrived for the local player. |
onShot(data) / onShotAt(x, y, data) | Projectiles. |
onMovementFinished() | A clientside this.move() with option 8 ended. |
setTimeout, setInterval and sleep work per NPC: callbacks keep this bound to the NPC, and the timers die when the NPC unloads (hot reload, or on the client when you leave the level). See the execution model.
The serverside this
Writes to the known properties of the serverside NpcThis replicate to everyone in the level:
ts
export function onCreated() {
this.image = 'images/sign.png' // '' = invisible
this.chat = 'Welcome to town!' // '' clears the bubble
this.nick = 'Tony' // name tag under the NPC; '' = none
this.dir = 2 // 0 up, 1 left, 2 down, 3 right
}| Member | What it does |
|---|---|
id, name | Runtime id; npc-<index> for level NPCs, localnpc-<id> for local NPCs. |
x, y | Position in tiles. Assigning teleports and cancels any move(). |
dir | Facing, Graal convention. |
image, chat | Sprite and chat bubble. |
nick | Name tag drawn under the NPC, like a player's nickname. '' (the default) shows no tag. Same rules as player nicks: control characters stripped, 40-character cap. |
nickcolor, nickshadow, nickshadowcolor | Name tag style: text color 'r,g,b' (default '89,194,191', teal), drop shadow on/off (default true), shadow color (default '52,89,88', dark teal) — NPC tags read apart from players' white ones by default. Invalid colors are ignored. |
showCharacter() | Draw the NPC as a gani character instead of an image. |
head, body, colors, ani, setAni(), aniParams | Character appearance; only visible after showCharacter(). setAni(name, ...params) passes setAni params to the gani's PARAM sprites. |
setShape() | The hitbox for triggerAction and projectiles. |
dontblock(), blockagain(), blocking | Collision, see Blocking. |
move() | Smooth movement, see Movement. |
level | The NPC's NpcLevel. |
join(), leave(), joinedclasses | Classes. |
destroy() | Remove a local NPC (returns false for level NPCs). |
A character NPC:
ts
export function onCreated() {
this.showCharacter()
this.head = 'head3.png'
this.body = 'body2.png'
this.colors[1] = '255,0,0' // coat; [0] skin, [2] sleeves, [3] shoes, [4] belt
this.dir = 2
this.setShape(0, 0, 32, 32) // 2×2 tiles
}Per-NPC state
Any property that isn't part of the API is a state bag private to this NPC and kept between handler calls — Graal's "state on this" convention:
ts
export function onActionTalk(player: Player) {
this.talks = (this.talks ?? 0) + 1
this.chat = `${player.nick}, you've talked to me ${this.talks} times`
}State-bag properties are not replicated and are not shared between the server and client halves; they are also lost when the NPC is re-created by a hot reload.
To share state with other NPCs, put it on this.level instead — see Shared level state.
Replicated state: this.attr
this.attr is the NPC version of player attributes. It's a JSON bag that only the server can write, and every client that can see the NPC receives it. The NPC's clientside script reads it as this.attr (read-only), for example to draw a healthbar:
ts
// Serverside
this.attr.hp = 100
this.attr.boss = { name: 'Slime King', phase: 1 }
delete this.attr.bossjs
// Clientside half of the same NPC
export function onUpdate() {
const hp = this.attr.hp ?? 0
// ...draw a bar with findimg
}- Same rules as player attributes. Values are JSON. Names are 1-128 characters, each value is up to 8192 characters, and the NPC's attributes total at most 16384 characters. Reassign nested values to write them. Assigning the value an attribute already has sends nothing.
- Shared by every handle. Attributes live on the NPC itself, so a putnpc handle and the NPC's own
thissee the same values (unlike the state bag). - Visibility follows the NPC. Clients get the current attributes with the NPC when they enter its level, or when it comes into their gmap window, and get each change after that.
- Not persisted. NPC attributes reset along with every other NPC property: when the level hot-reloads (local NPCs keep theirs) and when the server restarts.
- Attached ganis. A value naming a
.ganattaches that gani's script to the NPC on every client:this.attr.light = ['light.gan', 255, 0, 0]. Inside the script,playeris the NPC. See Attaching a gani with an attribute.
The clientside this
The clientside NpcThis has the same shape (x, y, dir, image, chat, nick, nickcolor, head, body, colors, ani, attr, showCharacter(), setAni(), move(), setShape(), dontblock(), …) but every write is local to this client: it changes what this player sees and nothing else. The server's copy stays the authority — a later serverside write or move overrides a client-local change. this.attr is the exception: it's read-only on the client, and assigning to it throws.
The clientside half also owns the NPC's light: drawaslight() with lightcolor, lightradius, lightshape and friends — see Lighting.
Client setShape doesn't change what triggers hit
The server hit-tests its own shapes for triggerAction and projectiles. Call setShape in the serverside half.
triggerAction: talking to an NPC
triggerAction(x, y, action, ...params) addresses NPCs by position: it fires onAction<Name> on every NPC whose shape contains the tile point (x, y). The action name gets its first letter uppercased ('openDoor' → onActionOpenDoor); characters other than letters, digits and _ are dropped.
Routing is strict, like Graal:
- Clientside
triggerActionsends the request to the server, which hit-tests its shapes and runs the serverside handler asonAction<Name>(player, ...params). Nothing runs clientside. - Serverside
this.level.triggerActionruns serverside handlers asonAction<Name>(...params)(no player) and the clientside handler of every hit NPC on every client in the level.
A "press A in front of an NPC" interaction, split across the two halves:
ts
// Clientside half: ask the server to act on whatever is in front of us.
const AHEAD = { up: [0, -2], left: [-2, 0], down: [0, 2], right: [2, 0] }
export function onKeyPressed(key: string) {
if (key !== 'A') return
const [dx, dy] = AHEAD[player.dir]
// player.x/y is the top-left of the 2×2 body; aim past its center.
triggerAction(player.x + 1 + dx, player.y + 1 + dy, 'talk')
}ts
// Serverside half of the target NPC.
export function onActionTalk(player: Player) {
this.chat = `Hello, ${player.nick}!`
}Params are JSON round-tripped, so only pass plain data.
Shapes
An NPC's shape defaults to its image's pixel size. An NPC with no image and no setShape has no shape, so no action or projectile can land on it — invisible "talk spots" (signs baked into the tileset, PCs) need an explicit this.setShape(0, 0, w, h). Shape values are pixels relative to the NPC's top-left; a tile is 16 pixels.
Calling triggerAction from a weapon
triggerAction is declared only for clientside NPC scripts, but the engine installs it as a global for every clientside script. A clientside weapon can use it after declaring it:
ts
declare function triggerAction(x: number, y: number, action: string, ...params: any[]): voidShared level state: NPCs talking to each other
triggerAction reaches NPCs by position. To reach them by name, use the level's shared state: any property you set on this.level that isn't one of its builtins is stored per level and visible to every serverside NPC in that level. Values are live JavaScript values — store an NPC's this and the other NPCs can read its properties and call its exported functions.
A door registers itself:
ts
// Door (serverside)
export function onCreated() {
this.image = 'images/door.png'
this.level.door = this
}
export function open() {
if (this.opened) return
this.opened = true
this.image = 'images/door-open.png'
this.dontblock()
setTimeout(() => close.call(this), 3000)
}
export function close() {
this.opened = false
this.image = 'images/door.png'
this.blockagain()
}and a pressure plate opens it:
ts
// Pressure plate (serverside)
export function onUpdate() {
if (this.level.players.some((p: Player) => standingOn(this, p)))
this.level.door?.open()
}- Register in
onCreated, and null-check when reading (this.level.door?.open()): the order NPCs are created in isn't guaranteed. - Calls run as the callee.
this.level.door.open()runsopenwiththis= the door, and timers,sleepand plain helper calls inside it belong to the door — just as if the door's own handler had called it. Errors thrown inside still propagate to the caller. - Builtins are reserved.
name,players,triggerAction,onwall,tiletype,shootandputnpcare read-only; assigning or deleting them throws.this.level.nameis always the level's real file name. - Per level. Each level — and each member level of a gmap — has its own state.
Object.keys(this.level),'door' in this.levelanddelete this.level.doorall work on it. - Cleared on hot reload. Saving the level wipes its shared state; the re-created level NPCs register again in
onCreated. Local NPCs survive the reload but must re-register themselves. - Serverside only. Clientside NPC scripts have no
this.level, and the player-scoped globallevel/player.leveldon't carry shared state. - Per instance, too. In an instance, each instanced copy of a level has its own state. For state shared by every level of an instance, use
this.instance.
Who's in the level: players
this.level.players is a fresh array of Player snapshots for everyone who has the level loaded. They're full player objects, client. / clientr. flags included. On a plain level that's everyone in it. On a gmap member it's every gmap player whose load window covers this member — so players standing in neighbouring members are included, not just the ones inside this .glvl.
Gmap players' x/y are gmap-global tiles, while the NPC's own x/y are member-local. Convert the NPC's position with leveltogmap, which returns null on a plain level (where both are already level-local):
ts
// Is the player's lower body (their walking footprint) on this 2×2 plate?
function standingOn(npc: NpcThis, p: Player): boolean {
const g = leveltogmap(npc.level.name, npc.x, npc.y)
const x = g ? g.x : npc.x
const y = g ? g.y : npc.y
return p.x + 2 > x && p.x < x + 2 && p.y + 2 > y && p.y + 1 < y + 2
}See the pressure plate & door tutorial for the full example.
To search by area instead, use findPlayersCircle and findPlayersRect. They take the NPC's member-local coordinates but search the whole gmap, and the players they return still carry gmap-global x/y:
ts
// Greet whoever walks up to the NPC, nearest first.
const near = this.level.findPlayersCircle(this.x + 1, this.y + 1, 3)
if (near.length > 0) this.chat = 'Hi ' + near[0].nick + '!'NpcLevel
this.level in a serverside NPC is an NpcLevel: the NPC's own level, in that level's local tile coordinates, plus its shared state.
| Member | Use |
|---|---|
name | The level's file name (the member .glvl on a gmap). Read-only. |
players | Players who have the level loaded (see above). |
triggerAction() | Fire actions at shapes (server + client handlers). |
onwall() | Is a rectangle blocked — by tiles, other blocking NPCs or players' lower bodies (never this NPC)? Out-of-level counts as blocked. |
tiletype() | The collision type of a tile. |
shoot() | Spawn a projectile (Projectiles). |
putnpc() | Spawn a local NPC. |
findPlayersCircle() / findPlayersRect() | Players in an area, searched across the whole gmap (Finding players). |
findPath() | An A* route around walls and other NPCs (Pathfinding). |
level vs this.level
The bare global level is player-scoped, meant for weapon and server scripts. It is a different object from this.level, even inside an NPC script. There, always use this.level: the global's shoot, putnpc and findPath return null, and players/findPlayers* return [].
Movement
this.move(dx, dy, time, options) glides the NPC by (dx, dy) tiles over time seconds. The server sends the move once and every client animates it on its own, so it is much cheaper than assigning x/y every tick. While a move runs, x/y read the interpolated position.
options is a bitmask:
| Bit | Name | Effect |
|---|---|---|
1 | cache | Queue behind pending moves instead of replacing them. |
2 | append | Measure dx/dy from the end of the queued path. |
4 | blockcheck | Stop at the last clear spot before a wall; drops the rest of the queue. |
8 | notify | Fire onMovementFinished when this move ends (reached or blocked). |
16 | apply direction | Face the move's dominant axis when it starts. |
time <= 0 moves instantly on the next update; assigning x or y cancels every pending move. A wandering NPC:
ts
export function onCreated() {
this.showCharacter()
this.homeX = this.x
this.homeY = this.y
// Hot reload re-fires onCreated: don't stack intervals.
if (this.wanderTimer) clearInterval(this.wanderTimer)
this.wanderTimer = setInterval(() => this.wander(), 2500)
}
export function wander() {
const d = Math.floor(Math.random() * 4)
const dx = [0, -2, 0, 2][d], dy = [-2, 0, 2, 0][d]
const nx = this.x + dx, ny = this.y + dy
if (Math.abs(nx - this.homeX) > 4 || Math.abs(ny - this.homeY) > 4) return
// The strip swept by the lower body; walls, NPCs and players block.
if (this.level.onwall(Math.min(this.x, nx), Math.min(this.y, ny) + 1,
2 + Math.abs(dx), 1 + Math.abs(dy))) return
this.dir = d
this.setAni('walk')
this.move(dx, dy, 0.35, 8)
}
export function onMovementFinished() {
this.setAni('idle')
}A clientside this.move() moves this client's copy only; its onMovementFinished fires on the client. Moves started serverside fire onMovementFinished serverside only.
Chasing a player
findPlayersCircle picks a target and findPath routes around walls and other NPCs. Re-planning on every step keeps the NPC on track as the player moves:
ts
// A character NPC that walks toward the nearest player within 12 tiles,
// re-planning its route around walls and other NPCs every step.
export function onCreated() {
this.showCharacter()
// Hot reload re-fires onCreated: don't stack intervals.
if (this.chaseTimer) clearInterval(this.chaseTimer)
this.chaseTimer = setInterval(() => this.chase(), 300)
}
export function chase() {
// Searched around the NPC's body center; nearest player first.
const target = this.level.findPlayersCircle(this.x + 1, this.y + 1, 12)[0]
if (!target) return this.setAni('idle')
// On a gmap the player's x/y are gmap-global while ours are
// member-local: subtract this member's origin (0 on a plain level).
const origin = leveltogmap(this.level.name, 0, 0)
const tx = target.x - (origin ? origin.x : 0)
const ty = target.y - (origin ? origin.y : 0)
// Walk with the lower body (2x1, one tile below x/y), like players do.
const path = this.level.findPath(this.x, this.y + 1, tx, ty + 1, { width: 2, height: 1 })
if (!path || path.length < 2) return this.setAni('idle')
// One tile toward the first waypoint; blockcheck (4) stops short of the
// player, and 16 turns the NPC to face the step.
const dx = Math.sign(path[1].x - path[0].x)
const dy = Math.sign(path[1].y - path[0].y)
this.setAni('walk')
this.move(dx, dy, 0.25, 4 | 16)
}Blocking
NPCs block by default, like walls: players can't walk through them, and blockcheck moves and onwall queries see them. What blocks:
- a character NPC (after
showCharacter()) blocks with its lower body — the same 2×1 footprint a player walks with; - anything else blocks with its shape (or image);
- an NPC with neither an image nor a shape never blocks.
Call this.dontblock() to let players and other NPCs walk through it (floor decals, ghosts, pickups) and this.blockagain() to undo it; this.blocking reads the current state. Serverside calls apply to everyone; the clientside dontblock() only affects the local player and that client's own NPC moves, and is overridden by the server's next change.
Projectiles and lights ignore NPCs
Projectile flight and light propagation test tiles only — a projectile flies through a blocking NPC unless it hits the NPC's shape (which fires onShot). Custom movement scripts that use onwall need their own escape rule for when an NPC ends up standing on the player.
Local NPCs (putnpc)
this.level.putnpc(x, y, serverScript, clientScript?) spawns a local NPC at runtime — Graal's putnpc2. Weapon and server scripts have the same thing on the player-scoped level.putnpc and on any player.level (gmap-global coordinates when on a gmap).
The scripts are TypeScript source strings, compiled through the same pipeline as level NPCs (identical sources are cached; the first compile of new source briefly blocks the server tick). The source can join a class, which keeps the string short:
ts
// In a serverside weapon handler: drop a flare that removes itself.
const npc = level.putnpc(player.x, player.y, `
export function onCreated() { this.join('flare') }
`)ts
// classes/flare.ts — serverside half
export function onCreated() {
setTimeout(() => this.destroy(), 100)
}Local NPCs are never saved to the level file. They live until destroy() or a server restart, and they survive level hot reloads. Staff with the clearnpcs right can remove strays with /clearnpcs <level> in RC.
putnpc returns the NPC's handle — the same API as its this — or null when the level can't be resolved. Set real properties on it directly:
ts
const n = this.level.putnpc(10, 12, 'export function onCreated() {}')
if (n) { n.image = 'images/chest.png'; n.chat = 'Loot!' }The handle and the script's this are different objects
Engine properties (x, image, chat, …) are shared, but state-bag properties are not: n.reward = 50 on the handle is invisible to the new NPC's script. The NPC's onCreated has also already run by the time putnpc returns. Bake configuration into the source instead:
ts
const cfg = JSON.stringify({ reward: 50 })
this.level.putnpc(10, 12, `
export function onCreated() { this.cfg = ${cfg}; this.join('chest') }
`)Editing level NPCs
Serverside scripts can read and change a level's baked NPCs — the ones stored in its .glvl — through any level object (player.level, findlevel(name), or an NPC's this.level), which is what an in-game NPC editor needs:
| Method | Does |
|---|---|
| getlevelnpcs() | Lists them as LevelNpcInfo — index, x, y, image and both script sources. |
| addlevelnpc(data, live?) | Appends one and returns its index (-1 on failure). |
| setlevelnpc(index, patch, live?) | Changes any of x, y, image, serverscript, clientscript (a LevelNpcPatch). |
| removelevelnpc(index, live?) | Removes one; later NPCs' indices shift down by one. |
| reloadlevelnpc(index) | Restarts just that NPC from the level's current state. |
Edits go into the level's in-memory copy, and the file only changes on savelevel(). By default they are staged: running NPCs keep their old scripts until reloadlevel() recreates them all (a hot reload without touching the file). To apply one NPC at a time, pass live = true to addlevelnpc/setlevelnpc/removelevelnpc, or call reloadlevelnpc(index) after staged edits:
- only that NPC restarts: its timers die, serverside
onCreatedruns again, thenonPlayerEntersfor every player who sees the level; - players get the fresh NPC, with its clientside script, without reloading the level. Other NPCs, putnpc locals and the level's shared state are left alone;
- a live remove takes the running NPC out of the level at once. resetlevel() throws the edits away. See Saving, reloading and resetting.
ts
// weapon server half of an NPC editor
export function onActionServerSide(player: Player, action: string, index: number, source: string) {
const lvl = player.level
if (!lvl || !player.hasstaffright('leveleditor')) return
if (action === 'list') {
triggerClient('weapon', this.name, 'npcs', lvl.getlevelnpcs())
} else if (action === 'setscript') {
lvl.setlevelnpc(index, { serverscript: source }, true) // restarts just this NPC
} else if (action === 'new') {
lvl.addlevelnpc({ x: player.x, y: player.y, serverscript: source }, true)
} else if (action === 'delete') {
lvl.removelevelnpc(index, true)
}
}- Indices are positions, not ids: after
removelevelnpc, re-readgetlevelnpcsbefore editing again. - Scripts aren't validated when you set them. A script that fails to compile just doesn't run after a reload;
saveleveltype-checks the level's scripts in the background and logs any errors to the server log. - Local NPCs from putnpc aren't part of the level and never appear here.
- An NPC that reloads or removes itself ends its own script.
onCreatedruns again on the fresh copy, so guard against reload loops. - On a gmap,
player.levelis the gmap and the NPC methods fail there — open the member withfindlevel(see Tile edits on a gmap).
Hot reload
Saving a level (GRC level editor, or any upload of the .glvl) hot-reloads it, and so does a script's reloadlevel() or resetlevel():
- every level NPC is unloaded — its timers die — and re-created, so serverside
onCreatedruns again andonPlayerEntersfires for everyone already in the level; - clients re-enter the level and get fresh copies; their clientside
onCreatedruns again; - local NPCs are kept.
State-bag properties don't survive the re-creation, and the level's shared state is cleared. Joined classes are re-joined because onCreated runs again — keep join() calls in onCreated.
Lib edits and NPCs
NPC scripts are compiled when their level is activated or reloaded. Editing a lib module or reloading scripts from RC does not recompile NPCs that are already running; re-save the level in GRC's Level Editor to pick up the change. Class edits, by contrast, are rebound live.
See also
- Classes — share NPC behaviour
- Levels & gmaps — coordinates, tiles,
onwall - Events & triggers —
triggerServer/triggerClientfor weapons - Reference: Serverside NPCs, Clientside NPCs