Skip to content

aispritejs: Sprite Animation State Machine

aispritejs is an input-driven 2D sprite animation runtime. You set inputs (speed, isGrounded, jump), and it decides which frame to play from a transition graph defined in JSON, so you never hard-code play("walk") in game logic.

The core is zero-dependency pure TypeScript with no renderer imports. The PixiJS v8 adapter is provided as a subpath export.

終端機視窗
npm install aispritejs
# The PixiJS adapter needs pixi.js installed separately (optional peer)
npm install pixi.js
inputs → [transition graph] → active state → (Δt) → active frame → adapter → texture
  • number input: a continuous value, such as speed
  • boolean input: a switch, such as isGrounded
  • trigger input: one-shot, reset automatically once consumed, such as jump, attack

Quick Start (pure core, zero dependencies)

Section titled “Quick Start (pure core, zero dependencies)”
import { createSpriteAnimator } from "aispritejs";
// The graph defines inputs, states, transitions, animations
const anim = createSpriteAnimator(graph);
// Set inputs
anim.setInput("speed", 4);
anim.setInput("isGrounded", true);
anim.fireTrigger("jump");
// Listen for state changes and for the end of non-loop clips
anim.onStateChange((to, from) => console.log(from, "→", to));
anim.onComplete((state) => console.log(state, "ended"));
// Call every frame in the render loop
anim.update(deltaMs);
const frameKey = anim.activeFrameKey; // Hand it to the renderer
import { Sprite, type Spritesheet } from "pixi.js";
import type { SpriteGraph } from "aispritejs";
import { createPixiSpriteAnimator } from "aispritejs/pixi";
declare const graph: SpriteGraph; // see "Transition Graph Example" below
declare const spritesheet: Spritesheet; // e.g. the result of await Assets.load("hero.json")
declare const deltaMs: number; // ms since the last frame, e.g. ticker.deltaMS
const sprite = new Sprite();
// The third argument (spritesheet here) is a PIXI.Spritesheet or a frameKey → Texture map
const view = createPixiSpriteAnimator(sprite, graph, spritesheet);
// Every frame: automatically switches sprite.texture to the current frame
view.update(deltaMs);
// Control inputs
view.setInput("speed", 4);
view.fireTrigger("jump");

Switching a character between idle, run and jump is the typical aispritejs job. Every frame in the demo below is drawn with Graphics and turned into a texture with generateTexture, and the resulting frameKey → Texture map goes to the adapter. The demo only sets speed and calls fireTrigger('jump') when you click or tap the canvas; the graph decides which frame plays, and the status line shows the active state and frame key.

Loading the interactive demo…

HeroSprite: an animation state graph driven by the Pixi adapter
Demo source
src/demos/sprite-animator.ts
/**
* HeroSprite: an aispritejs animation state graph driven by the PixiJS adapter.
*
* The hero's frames are drawn with Graphics and rendered to textures, which gives the adapter
* the frameKey -> Texture map it takes as its third argument. The demo only sets inputs:
* - `speed` (number): the hero runs from one end of the ground to the other, rests, and turns;
* - `jump` (trigger): a click or tap on the canvas fires it.
* The graph decides the rest: idle <-> run follows `speed`, an Any-State (`from: "*"`) edge with
* a higher priority wins for `jump`, and the non-looping jump clip returns to idle via `onEnd`.
* The readout shows the animator's active state and frame key.
*/
import type { SpriteGraph } from 'aispritejs';
import { createPixiSpriteAnimator } from 'aispritejs/pixi';
import { Container, Graphics, Rectangle, Sprite, type Application, type Texture } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const GROUND_Y = 330;
const PATROL = { left: 150, right: 650 };
const RUN_SPEED = 170; // px per second
const REST_MS = 900; // idle time at each end of the patrol
const JUMP_HEIGHT = 90;
const FRAME = { width: 48, height: 64 }; // every frame texture has this size, feet at the bottom
const HERO_SCALE = 1.8;
const MAX_STEP_MS = 50;
const graph: SpriteGraph = {
inputs: {
speed: { type: 'number', default: 0 },
jump: { type: 'trigger' },
},
initial: 'idle',
states: {
idle: { animation: 'idle', loop: true },
run: { animation: 'run', loop: true },
jump: { animation: 'jump', loop: false, onEnd: 'idle' },
},
transitions: [
{ from: 'idle', to: 'run', when: [{ input: 'speed', op: 'GreaterThan', value: 0 }] },
{ from: 'run', to: 'idle', when: [{ input: 'speed', op: 'Equals', value: 0 }] },
// Any State: jump wins over the speed edges above when both hold in the same update.
{ from: '*', to: 'jump', when: [{ input: 'jump', op: 'Trigger' }], priority: 1 },
],
animations: {
idle: ['idle_0', 'idle_1'],
run: ['run_0', 'run_1', 'run_2', 'run_3'],
jump: ['jump_0', 'jump_1', 'jump_2', 'jump_3'],
},
frames: {
idle_0: { duration: 450 },
idle_1: { duration: 450 },
jump_0: { duration: 70 }, // crouch
jump_1: { duration: 220 }, // rise
jump_2: { duration: 220 }, // fall
jump_3: { duration: 90 }, // land
},
defaultFrameDuration: 110,
};
const JUMP_AIR = { start: 70, duration: 440 }; // the rise and fall frames, in ms from the jump start
/**
* One pose: upper-body bob in px, leg and arm angles in radians (0 = straight down), leg length.
* The hip height follows from the legs, so the lower foot always touches the frame bottom.
*/
type Pose = [bob: number, legA: number, legB: number, armA: number, armB: number, legLength: number];
const POSES: Record<string, Pose> = {
idle_0: [0, 0.12, -0.12, 0.15, -0.15, 20],
idle_1: [1, 0.12, -0.12, 0.2, -0.2, 20],
run_0: [0, 0.6, -0.6, -0.7, 0.7, 20],
run_1: [-1, 0.2, -0.2, -0.2, 0.2, 20],
run_2: [0, -0.6, 0.6, 0.7, -0.7, 20],
run_3: [-1, -0.2, 0.2, 0.2, -0.2, 20],
jump_0: [0, 0.5, -0.5, -0.6, -0.9, 15],
jump_1: [-3, 0.3, -0.1, 2.6, 2.3, 18],
jump_2: [-1, 0.5, 0.1, 1.6, 1.3, 16],
jump_3: [0, 0.45, -0.45, 0.4, -0.4, 16],
};
/** Draws one white frame (tinted later) facing right: head with an eye cut out, torso, limbs. */
function drawPose(g: Graphics, [bob, legA, legB, armA, armB, legLength]: Pose): void {
const limb = (x: number, y: number, angle: number, length: number) =>
g.moveTo(x, y).lineTo(x + Math.sin(angle) * length, y + Math.cos(angle) * length);
const hipY = FRAME.height - 3 - legLength * Math.cos(Math.max(Math.abs(legA), Math.abs(legB)));
const y = hipY - 41 + bob; // upper-body offset from the standing pose
g.circle(24, 13 + y, 9).fill(0xffffff).circle(28, 12 + y, 2).cut();
g.roundRect(17, 23 + y, 14, 20, 5).fill(0xffffff);
limb(24, hipY, legA, legLength);
limb(24, hipY, legB, legLength);
limb(24, 27 + y, armA, 13);
limb(24, 27 + y, armB, 13);
g.stroke({ width: 5, color: 0xffffff, cap: 'round' });
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
hero: cssColor('--sl-color-accent'),
ground: cssColor('--sl-color-gray-4'),
shadow: cssColor('--sl-color-gray-3'),
};
}
const READOUT = {
'zh-TW': (state: string, frame: string) => `狀態:${state}|frame:${frame}|點擊或輕觸畫面觸發 jump`,
en: (state: string, frame: string) => `State: ${state} | frame: ${frame} | click or tap to jump`,
};
export function mount(app: Application, { lang, setStatus, cssColor, signal }: DemoContext): DemoHandle {
// 1. Frame textures, keyed by the frame keys the graph's animations use.
const textures: Record<string, Texture> = {};
for (const [key, pose] of Object.entries(POSES)) {
const g = new Graphics();
drawPose(g, pose);
const frame = new Rectangle(0, 0, FRAME.width, FRAME.height); // same size for every frame
textures[key] = app.renderer.generateTexture({ target: g, frame, resolution: 3, antialias: true });
g.destroy();
}
// 2. Scene: ground, a shadow that shrinks while airborne, and the hero sprite.
const arena = new Container();
const ground = new Graphics();
const shadow = new Graphics();
const hero = new Sprite();
hero.anchor.set(0.5, 1); // feet on the ground; the frames carry no atlas anchor
hero.scale.set(HERO_SCALE);
arena.addChild(ground, shadow, hero);
app.stage.addChild(arena);
// 3. The adapter validates the graph and every frame key, then owns hero.texture.
const view = createPixiSpriteAnimator(hero, graph, textures);
let colors = readColors(cssColor);
const paint = () => {
ground.clear().moveTo(40, GROUND_Y).lineTo(ARENA.width - 40, GROUND_Y).stroke({ width: 2, color: colors.ground });
shadow.clear().ellipse(0, 0, 26, 6).fill({ color: colors.shadow, alpha: 0.35 });
hero.tint = colors.hero;
};
const fit = () => {
const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height);
arena.scale.set(scale);
arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2);
};
fit();
app.renderer.on('resize', fit);
// Gameplay state the demo owns; the animator only ever sees it through inputs.
let x = PATROL.left;
let direction = 1;
let restLeft = REST_MS;
let jumpClock = 0; // ms since the current jump started
let shownFrame = '';
view.onStateChange((to) => {
if (to === 'jump') jumpClock = 0;
}, { signal });
const jump = () => {
// No double jump: a trigger fired mid-air would restart the clip through the Any-State edge.
if (view.activeState !== 'jump') view.fireTrigger('jump');
};
app.canvas.addEventListener('pointerdown', jump);
app.canvas.style.cursor = 'pointer';
/** Places the hero and its shadow, and refreshes the readout when the frame changes. */
const place = () => {
const t = Math.min(Math.max((jumpClock - JUMP_AIR.start) / JUMP_AIR.duration, 0), 1);
const height = view.activeState === 'jump' ? 4 * JUMP_HEIGHT * t * (1 - t) : 0;
hero.position.set(x, GROUND_Y - height);
hero.scale.x = HERO_SCALE * direction;
shadow.position.set(x, GROUND_Y);
shadow.scale.set(1 - (height / JUMP_HEIGHT) * 0.5);
if (view.activeFrameKey !== shownFrame) {
shownFrame = view.activeFrameKey;
setStatus(READOUT[lang](view.activeState, shownFrame));
}
};
paint();
place(); // the first frame is drawn even if the demo never plays (reduced motion)
return {
update(deltaMS) {
const ms = Math.min(deltaMS, MAX_STEP_MS);
if (restLeft > 0) {
restLeft -= ms;
if (restLeft <= 0) direction = x <= PATROL.left ? 1 : -1; // turn around and run back
} else {
x += direction * RUN_SPEED * (ms / 1000);
if (x <= PATROL.left || x >= PATROL.right) {
x = Math.min(Math.max(x, PATROL.left), PATROL.right);
restLeft = REST_MS;
}
}
view.setInput('speed', restLeft > 0 ? 0 : RUN_SPEED);
view.update(ms); // evaluates transitions, advances the clip, swaps hero.texture
jumpClock += ms;
place();
},
onThemeChange() {
colors = readColors(cssColor);
paint();
},
dispose() {
app.renderer.off('resize', fit);
app.canvas.removeEventListener('pointerdown', jump);
app.canvas.style.cursor = '';
view.dispose(); // releases the animator; the sprite is ours to destroy
arena.destroy({ children: true });
for (const texture of Object.values(textures)) texture.destroy(true);
},
};
}
const graph = {
inputs: {
speed: { type: "number", default: 0 },
isGrounded: { type: "boolean", default: true },
jump: { type: "trigger" },
},
initial: "idle",
states: {
idle: { animation: "idle", loop: true },
walk: { animation: "walk", loop: true },
jump: { animation: "jump", loop: false, onEnd: "idle" },
},
transitions: [
{ from: "idle", to: "walk", when: [{ input: "speed", op: "GreaterThan", value: 0 }] },
{ from: "walk", to: "idle", when: [{ input: "speed", op: "Equals", value: 0 }] },
{ from: "*", to: "jump", when: [{ input: "jump", op: "Trigger" }] },
],
animations: {
idle: ["idle_0", "idle_1", "idle_2"],
walk: ["walk_0", "walk_1", "walk_2", "walk_3"],
jump: ["jump_0", "jump_1", "jump_2"],
},
};
  • update() / reset() (the same in the core and the Pixi adapter) run to completion: an update() / reset() called inside onStateChange / onComplete is queued and runs after the current update (including the onEnd automatic transition) has finished. So calling reset() inside onComplete first receives onStateChange(onEndTarget, from), then onStateChange(initial, onEndTarget). Read activeState after the outermost update() returns, and put try/catch around the outermost call; calling dispose() inside a listener stops the current update immediately.
  • initial, a state’s animation / onEnd, a transition’s from / to, and a condition’s input / op must all be strings, and a transition priority must be an integer (negative numbers and 0 are fine). When the graph’s structure or content is invalid, createSpriteAnimator(), loadAtlas() and createPixiSpriteAnimator() throw InvalidGraphError and no animator is created. Convert a priority read from JSON with Number() and round it to an integer first.
  • The Pixi adapter requires every frame key of every animation to exist in the texture map / spritesheet. An entry whose value is null / undefined also counts as missing, and MissingTextureError is thrown at construction.
  • parseAtlas(atlas, control?) also performs a structure check on an explicitly passed control, and throws InvalidAtlasError on failure.
Subpath Purpose
aispritejs Core: createSpriteAnimator
aispritejs/pixi PixiJS v8 adapter: createPixiSpriteAnimator
aispritejs/atlas Atlas parsing helpers
aispritejs/schema JSON Schema for the JSON graph (for validating design tool output)
  • With aiecsjs: each entity carries a SpriteAnimator, and an ECS system updates it every frame and reads activeFrameKey
  • With aifsmjs: the game-logic FSM decides behaviour and outputs inputs to the SpriteAnimator, which decides the visuals
  • Standalone: UI animation, character selection screens and so on, where no ECS is needed