跳到內容

aispritejs — Sprite 動畫狀態機

aispritejs 是一個輸入驅動的 2D sprite 動畫 runtime。你設定 inputs(speed、isGrounded、jump),它根據 JSON 定義的 transition graph 決定當前要播哪個 frame,不需要在遊戲邏輯裡硬寫 play("walk")。

核心是零依賴的純 TypeScript,不含任何 renderer import。PixiJS v8 adapter 以 subpath export 提供。

終端機視窗
npm install aispritejs
# PixiJS adapter 需要額外安裝 pixi.js(optional peer)
npm install pixi.js
inputs → [transition graph] → active state → (Δt) → active frame → adapter → texture
  • number input:連續值,如 speed
  • boolean input:開關,如 isGrounded
  • trigger input:一次性,消耗後自動 reset,如 jump、attack
import { createSpriteAnimator } from "aispritejs";
// graph 定義:inputs、states、transitions、animations
const anim = createSpriteAnimator(graph);
// 設定 inputs
anim.setInput("speed", 4);
anim.setInput("isGrounded", true);
anim.fireTrigger("jump");
// 監聽狀態切換與非 loop clip 結束
anim.onStateChange((to, from) => console.log(from, "→", to));
anim.onComplete((state) => console.log(state, "結束"));
// 在 render loop 每幀呼叫
anim.update(deltaMs);
const frameKey = anim.activeFrameKey; // 交給 renderer 使用
import { Sprite, type Spritesheet } from "pixi.js";
import type { SpriteGraph } from "aispritejs";
import { createPixiSpriteAnimator } from "aispritejs/pixi";
declare const graph: SpriteGraph; // 見下方「Transition graph 結構範例」
declare const spritesheet: Spritesheet; // 例如 await Assets.load("hero.json") 的結果
declare const deltaMs: number; // 上一幀經過的毫秒數,例如 ticker.deltaMS
const sprite = new Sprite();
// 第三個參數(此處為 spritesheet)是 PIXI.Spritesheet 或 frameKey → Texture map
const view = createPixiSpriteAnimator(sprite, graph, spritesheet);
// 每幀:自動切換 sprite.texture 到當前 frame
view.update(deltaMs);
// 控制 inputs
view.setInput("speed", 4);
view.fireTrigger("jump");

角色在待機、奔跑、跳躍之間切換是 aispritejs 最典型的用法。下方示範的每個 frame 都先用 Graphics 畫好,再以 generateTexture 轉成 texture,組成 frameKey → Texture map 交給 adapter;示範程式只設定 speed,並在點擊或輕觸畫面時呼叫 fireTrigger('jump'),要播哪個 frame 全由 graph 決定,狀態列顯示目前的 state 與 frame key。

互動示範載入中…

HeroSprite:Pixi adapter 驅動的動畫狀態圖
示範原始碼
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()(核心與 Pixi adapter 皆同)採 run-to-completion:在 onStateChange / onComplete 內呼叫的 update() / reset() 會排入佇列,等目前這次 update(包含 onEnd 自動轉場)結束後才執行。因此在 onComplete 內呼叫 reset() 會先收到 onStateChange(onEndTarget, from),再收到 onStateChange(initial, onEndTarget)。請在最外層 update() 回傳後再讀 activeState,並把 try/catch 放在最外層呼叫;在 listener 內呼叫 dispose() 則會立刻停止這次 update。
  • initial、state 的 animation / onEnd、transition 的 from / to、condition 的 input / op 都必須是 string,transition priority 必須是整數(負數與 0 也可以)。graph 結構或內容無效時,createSpriteAnimator()、loadAtlas() 與 createPixiSpriteAnimator() 丟出 InvalidGraphError,不會建立 animator。從 JSON 讀進來的 priority 請先用 Number() 轉換並取整。
  • Pixi adapter 要求每個 animation 的每個 frame key 都存在於 texture map / spritesheet,值為 null / undefined 的 entry 也視為缺少,會在建構時丟出 MissingTextureError。
  • parseAtlas(atlas, control?) 對明確傳入的 control 也會做結構檢查,錯誤時丟出 InvalidAtlasError。
Subpath 用途
aispritejs 核心:createSpriteAnimator
aispritejs/pixi PixiJS v8 adapter:createPixiSpriteAnimator
aispritejs/atlas Atlas 解析輔助
aispritejs/schema JSON graph 的 JSON Schema(用於驗證設計工具輸出)
  • 與 aiecsjs 搭配:每個 entity 帶一個 SpriteAnimator,ECS system 每幀 update 並取 activeFrameKey
  • 與 aifsmjs 搭配:遊戲邏輯 FSM 決定行為,輸出 inputs 給 SpriteAnimator 決定視覺
  • 獨立使用:UI 動畫、角色選擇畫面等,不需要 ECS