Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(examples): sprite-animation rides the Animator state machine

yhhfebc6b03ff22
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 83d72a582..ff726cdfb 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -135,6 +135,12 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {
const exec = (code: string): Promise<unknown> =>
w.webContents.executeJavaScript(code, true).catch(() => undefined);
+ // Pipe renderer console (all frames, incl. the play OOPIF) to the shot log —
+ // headless failures otherwise die silently inside the window.
+ w.webContents.on('console-message', (_e, level, message) => {
+ if (level >= 2) console.log(`[console:${level === 3 ? 'error' : 'warn'}]`, message);
+ });
+
// Deterministic waits — poll a real in-page condition instead of guessing at a
// wall-clock delay (the delay is either flaky-short on a slow machine or wasted
// on a fast one). Returns false + warns on timeout so a screenshot of a
@@ -231,6 +237,22 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {
}
await settleFrames(8); // let a kinetic fling play out before the capture
}
+ // Eval INSIDE the play realm (the estella:// OOPIF) — the same main-process
+ // frame routing as SHOT_DRAG, since neither SHOT_EVAL nor sendInputEvent can
+ // reach the iframe. Lets a shot drive gameplay input, e.g. dispatching
+ // KeyboardEvents on the frame's document.
+ if (process.env.ESTELLA_SHOT_PLAY_EVAL) {
+ const playFrame = w.webContents.mainFrame.frames.find((f) => f.url.startsWith('estella://'));
+ if (!playFrame) {
+ console.log('[playEval] no estella:// play frame found');
+ } else {
+ const result = await playFrame
+ .executeJavaScript(process.env.ESTELLA_SHOT_PLAY_EVAL)
+ .catch((e: Error) => `error: ${e.message}`);
+ console.log('[playEval]', typeof result === 'string' ? result : JSON.stringify(result));
+ await settleFrames(8);
+ }
+ }
if (process.env.ESTELLA_SHOT_EVAL) {
const result = await exec(process.env.ESTELLA_SHOT_EVAL);
console.log('[eval]', typeof result === 'string' ? result : JSON.stringify(result));
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 67adf94c5..144c2825e 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -194,6 +194,10 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
physicsConfig: msg.physicsConfig,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
+ // Realm-local debug handle for automation/diagnostics (mirrors the headless
+ // host's __estellaHeadless): the editor can't reach into this OOPIF except by
+ // main-process frame eval, and the eval needs SOMETHING to query.
+ (window as unknown as { __estellaPlay?: unknown }).__estellaPlay = { app };
}
async function boot(msg: InitMessage): Promise<void> {
diff --git a/examples/sprite-animation/README.md b/examples/sprite-animation/README.md
new file mode 100644
index 000000000..86e43b494
--- /dev/null
+++ b/examples/sprite-animation/README.md
@@ -0,0 +1,58 @@
+# Sprite Animation
+
+The engine's frame-animation stack in one controllable scene: `.esanim` clips,
+the `SpriteAnimator` playback channel, the **Animator state machine** (Unity
+Animator model: parameters, triggers, 1D blend, exit time) on top of it, and
+**frame events** turned into gameplay.
+
+## Controls
+
+| Input | Action |
+| ---------------- | ----------------------------------------- |
+| ←/→ or A/D | Walk (the sprite flips with direction) |
+| hold Shift | Run — the Move blend crosses its threshold and re-selects the walk clip at 1.9× |
+| Space | Hop — a trigger fires a non-looping clip; its exit time returns to Idle |
+
+## How it works
+
+- **Clips, two authoring paths** — `idle`/`walk` load from `.esanim` assets
+ referenced by the scene; the `hop` clip is registered from code at startup
+ (`SpriteAnimation.registerClip`), built out of frames the asset clips already
+ loaded (`src/systems/setup.ts`).
+- **The state machine** (`setup.ts`) declares a `speed` float and a `hop`
+ trigger. `Idle ↔ Move` transitions compare `speed` against enter/exit
+ thresholds; `Move` is a **1D blend** whose thresholds pick the walk clip at
+ 1.0× or 1.9× playback as `speed` rises — idle→walk→run from one parameter.
+ `Hop` plays a non-looping clip and its `hasExitTime` transition auto-advances
+ back to `Idle` when the clip finishes.
+- **Control** (`src/systems/control.ts`) never touches the `SpriteAnimator`:
+ it eases a velocity, writes `|vx|` into the `speed` parameter
+ (`AnimatorController.setFloat`) and Space into the trigger (`setTrigger`).
+ The state machine picks every clip — gameplay code and animation selection
+ stay decoupled.
+- **Frame events** (`setup.ts` + `src/systems/puffs.ts`) — the walk clip's two
+ contact frames carry a `footstep` event; a global listener queues each one
+ and `puffSystem` spawns a fading dust puff at the feet through `Commands`.
+- The two **bystander aliens** run plain `SpriteAnimator` clips at their own
+ speeds — the playback channel needs no state machine when a loop is all you
+ want.
+
+Play the scene in the editor and select the Player while it runs: the Details
+panel shows `Animator.currentState` flipping between `Idle`, `Move`, and `Hop`
+live.
+
+## Files
+
+```
+assets/
+ animations/ # idle.esanim, walk.esanim (the hop clip is code-registered)
+ scenes/main.esscene # camera, ground, the FSM-driven player, two bystanders
+src/
+ main.ts # registers the systems
+ config.ts # tuning (speeds, thresholds, hop arc, puff life)
+ components.ts # Player, Puff, the footstep event queue
+ systems/
+ setup.ts # controller definition + hop clip + footstep events
+ control.ts # input → movement + Animator parameters
+ puffs.ts # footstep events → dust puffs
+```
diff --git a/examples/sprite-animation/assets/scenes/main.esscene b/examples/sprite-animation/assets/scenes/main.esscene
index 63138af2e..492d61a5a 100644
--- a/examples/sprite-animation/assets/scenes/main.esscene
+++ b/examples/sprite-animation/assets/scenes/main.esscene
@@ -8,87 +8,193 @@
"parent": null,
"children": [],
"components": [
- { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
- { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 300,
+ "isActive": true,
+ "priority": 0
+ }
+ }
],
"visible": true
},
{
"id": 1,
- "name": "Character0",
+ "name": "Ground",
"parent": null,
"children": [],
"components": [
- { "type": "Transform", "data": { "position": { "x": -240, "y": 0, "z": 0 } } },
- { "type": "Sprite", "data": { "size": { "x": 72, "y": 98 } } },
- { "type": "SpriteAnimator", "data": {
- "clip": "assets/animations/walk.esanim",
- "speed": 0.8
- }},
- { "type": "AnimSwitcher", "data": { "switchTimer": 2 } }
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": -84,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": {
+ "x": 700,
+ "y": 16
+ },
+ "color": {
+ "r": 0.16,
+ "g": 0.19,
+ "b": 0.26,
+ "a": 1
+ },
+ "layer": 1
+ }
+ }
],
"visible": true
},
{
"id": 2,
- "name": "Character1",
+ "name": "Player",
"parent": null,
"children": [],
"components": [
- { "type": "Transform", "data": { "position": { "x": -120, "y": 0, "z": 0 } } },
- { "type": "Sprite", "data": { "size": { "x": 72, "y": 98 } } },
- { "type": "SpriteAnimator", "data": {
- "clip": "assets/animations/idle.esanim"
- }},
- { "type": "AnimSwitcher", "data": { "isWalking": false, "switchTimer": 2.5 } }
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": -27,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": {
+ "x": 72,
+ "y": 98
+ },
+ "layer": 5,
+ "texture": "assets/textures/idle_0.png"
+ }
+ },
+ {
+ "type": "SpriteAnimator",
+ "data": {
+ "clip": "assets/animations/idle.esanim"
+ }
+ },
+ {
+ "type": "Animator",
+ "data": {
+ "controller": "alien"
+ }
+ },
+ {
+ "type": "Player",
+ "data": {}
+ }
],
"visible": true
},
{
"id": 3,
- "name": "Character2",
+ "name": "Bystander",
"parent": null,
"children": [],
"components": [
- { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
- { "type": "Sprite", "data": { "size": { "x": 72, "y": 98 } } },
- { "type": "SpriteAnimator", "data": {
- "clip": "assets/animations/walk.esanim",
- "speed": 1.2
- }},
- { "type": "AnimSwitcher", "data": {} }
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -260,
+ "y": -27,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": {
+ "x": 72,
+ "y": 98
+ },
+ "color": {
+ "r": 0.78,
+ "g": 0.82,
+ "b": 0.88,
+ "a": 1
+ },
+ "layer": 4,
+ "texture": "assets/textures/idle_0.png"
+ }
+ },
+ {
+ "type": "SpriteAnimator",
+ "data": {
+ "clip": "assets/animations/idle.esanim",
+ "speed": 0.75
+ }
+ }
],
"visible": true
},
{
"id": 4,
- "name": "Character3",
+ "name": "Pacer",
"parent": null,
"children": [],
"components": [
- { "type": "Transform", "data": { "position": { "x": 120, "y": 0, "z": 0 } } },
- { "type": "Sprite", "data": { "size": { "x": 72, "y": 98 } } },
- { "type": "SpriteAnimator", "data": {
- "clip": "assets/animations/idle.esanim",
- "speed": 1.4
- }},
- { "type": "AnimSwitcher", "data": { "isWalking": false, "switchTimer": 3.5 } }
- ],
- "visible": true
- },
- {
- "id": 5,
- "name": "Character4",
- "parent": null,
- "children": [],
- "components": [
- { "type": "Transform", "data": { "position": { "x": 240, "y": 0, "z": 0 } } },
- { "type": "Sprite", "data": { "size": { "x": 72, "y": 98 } } },
- { "type": "SpriteAnimator", "data": {
- "clip": "assets/animations/walk.esanim",
- "speed": 1.6
- }},
- { "type": "AnimSwitcher", "data": { "switchTimer": 4 } }
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 260,
+ "y": -27,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": {
+ "x": 72,
+ "y": 98
+ },
+ "color": {
+ "r": 0.78,
+ "g": 0.82,
+ "b": 0.88,
+ "a": 1
+ },
+ "flipX": true,
+ "layer": 4,
+ "texture": "assets/textures/walk_0.png"
+ }
+ },
+ {
+ "type": "SpriteAnimator",
+ "data": {
+ "clip": "assets/animations/walk.esanim",
+ "speed": 1.25
+ }
+ }
],
"visible": true
}
diff --git a/examples/sprite-animation/project.esproject b/examples/sprite-animation/project.esproject
index 1f5426bc3..b857a47da 100644
--- a/examples/sprite-animation/project.esproject
+++ b/examples/sprite-animation/project.esproject
@@ -1,7 +1,7 @@
{
"formatVersion": "1",
"name": "Sprite Animation",
- "description": "Frame-based sprite animation driven by .esanim clips and a state switcher.",
+ "description": "Frame animation, bottom to top: .esanim clips, SpriteAnimator playback, an Animator state machine (speed blend + hop trigger + exit time), and footstep frame events. Arrows/A-D walk, Shift runs, Space hops.",
"tag": "Animation",
"version": "0.1.0",
"defaultScene": "assets/scenes/main.esscene",
diff --git a/examples/sprite-animation/src/components.ts b/examples/sprite-animation/src/components.ts
index 3bc717b26..b14bd53f1 100644
--- a/examples/sprite-animation/src/components.ts
+++ b/examples/sprite-animation/src/components.ts
@@ -1,8 +1,18 @@
import { defineComponent } from 'esengine';
-export const AnimSwitcher = defineComponent('AnimSwitcher', {
- walkClip: 'assets/animations/walk.esanim',
- idleClip: 'assets/animations/idle.esanim',
- isWalking: true,
- switchTimer: 3,
+// The controllable character. `vx` is the eased horizontal velocity (its
+// magnitude feeds the Animator's `speed` parameter); `hopTime` tracks the
+// vertical arc while the Hop state plays.
+export const Player = defineComponent('Player', {
+ vx: 0,
+ hopTime: 0,
});
+
+// A footstep dust puff — fades and rises over its short life.
+export const Puff = defineComponent('Puff', {
+ life: 0.5,
+});
+
+// Walk-clip frame events land here (the listener fires inside the animation
+// update, so spawning is deferred to puffSystem's Commands the same frame).
+export const footsteps = { pending: 0 };
diff --git a/examples/sprite-animation/src/config.ts b/examples/sprite-animation/src/config.ts
new file mode 100644
index 000000000..9db99267d
--- /dev/null
+++ b/examples/sprite-animation/src/config.ts
@@ -0,0 +1,36 @@
+// Shared tuning for the sprite-animation showcase.
+
+// Clips loaded from .esanim assets are registered under their project path.
+export const CLIP_IDLE = 'assets/animations/idle.esanim';
+export const CLIP_WALK = 'assets/animations/walk.esanim';
+// The hop clip is registered from code at startup (see systems/setup.ts) —
+// the second authoring path: a SpriteAnimClip built out of already-loaded frames.
+export const CLIP_HOP = 'hop';
+
+// The controller name the scene's Animator component references.
+export const CONTROLLER = 'alien';
+
+// Movement (world px). `speed` is also the Animator's float parameter, so the
+// blend threshold below is in the same unit.
+export const WALK_SPEED = 110;
+export const RUN_SPEED = 210;
+export const ACCEL = 900;
+/** Above this |speed| the Move blend selects the fast (run) row. */
+export const RUN_BLEND_AT = 150;
+/** Idle↔Move hysteresis thresholds on the `speed` parameter. */
+export const MOVE_ENTER = 20;
+export const MOVE_EXIT = 15;
+/** How far the player may roam from the centre. */
+export const RANGE_X = 180;
+
+// Hop: a short arc in code while the Hop state plays its non-looping clip.
+// Duration matches the clip's summed frame durations, so the arc lands exactly
+// when the exit-time transition returns the state machine to Idle.
+export const HOP_DURATION = 0.44;
+export const HOP_HEIGHT = 46;
+
+// Footstep dust (spawned by the walk clip's frame events).
+export const PUFF_LIFE = 0.5;
+
+/** Standing baseline: feet rest on the ground bar. */
+export const BASE_Y = -27;
diff --git a/examples/sprite-animation/src/main.ts b/examples/sprite-animation/src/main.ts
index db9b4ed7a..c1b89a5f3 100644
--- a/examples/sprite-animation/src/main.ts
+++ b/examples/sprite-animation/src/main.ts
@@ -1,6 +1,26 @@
-import { addSystemToSchedule, Schedule } from 'esengine';
+// Sprite Animation — the engine's frame-animation stack, bottom to top:
+//
+// • .esanim clips — idle/walk load from assets with the scene; the hop
+// clip is registered from code (both authoring paths).
+// • SpriteAnimator — frame playback. The two background aliens run plain
+// clips at their own speeds, no state machine involved.
+// • Animator (FSM) — the player is driven by a state machine: a `speed`
+// float switches Idle↔Move, Move is a 1D blend that
+// re-selects walk×1.0 / walk×1.9 (run) as speed rises,
+// and the Space `hop` trigger plays a non-looping clip
+// whose exit time auto-returns to Idle.
+// • Frame events — the walk clip's contact frames fire `footstep`
+// events; a system turns them into fading dust puffs.
+//
+// Controls: ←/→ or A/D walk · hold Shift to run · Space to hop.
+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';
import './components';
-import { switchSystem } from './systems/switch';
+import { setupSystem, wireClipsSystem } from './systems/setup';
+import { controlSystem } from './systems/control';
+import { puffSystem } from './systems/puffs';
-addSystemToSchedule(Schedule.Update, switchSystem);
+addStartupSystem(setupSystem);
+addSystemToSchedule(Schedule.Update, wireClipsSystem);
+addSystemToSchedule(Schedule.Update, controlSystem);
+addSystemToSchedule(Schedule.Update, puffSystem);
diff --git a/examples/sprite-animation/src/systems/control.ts b/examples/sprite-animation/src/systems/control.ts
new file mode 100644
index 000000000..8bff2c8ec
--- /dev/null
+++ b/examples/sprite-animation/src/systems/control.ts
@@ -0,0 +1,51 @@
+import {
+ defineSystem, Query, Mut, Res, Time, Input,
+ Transform, Sprite, Animator,
+ AnimatorController, AnimatorControllerApi,
+} from 'esengine';
+import { Player } from '../components';
+import {
+ WALK_SPEED, RUN_SPEED, ACCEL, RANGE_X,
+ HOP_DURATION, HOP_HEIGHT, BASE_Y,
+} from '../config';
+
+// Input → movement + Animator parameters. The system never touches the
+// SpriteAnimator: it eases a velocity, feeds |vx| into the `speed` float and
+// Space into the `hop` trigger — the state machine picks every clip.
+export const controlSystem = defineSystem(
+ [Query(Mut(Transform), Mut(Sprite), Mut(Player), Animator), Res(Input), Res(Time), Res(AnimatorController)],
+ (players, input, time, ctrl: AnimatorControllerApi) => {
+ const dir =
+ (input.isKeyDown('ArrowRight') || input.isKeyDown('KeyD') ? 1 : 0) -
+ (input.isKeyDown('ArrowLeft') || input.isKeyDown('KeyA') ? 1 : 0);
+ const running = input.isKeyDown('ShiftLeft') || input.isKeyDown('ShiftRight');
+ const hop = input.isKeyPressed('Space');
+
+ for (const [entity, transform, sprite, player, animator] of players) {
+ // Ease toward the wanted velocity so the speed parameter sweeps
+ // through the run blend threshold instead of jumping across it.
+ const target = dir * (running ? RUN_SPEED : WALK_SPEED);
+ const dv = target - player.vx;
+ const step = ACCEL * time.delta;
+ player.vx += Math.abs(dv) <= step ? dv : Math.sign(dv) * step;
+
+ transform.position.x = Math.max(-RANGE_X, Math.min(RANGE_X, transform.position.x + player.vx * time.delta));
+ if (dir !== 0) sprite.flipX = dir < 0;
+
+ ctrl.setFloat(entity, 'speed', Math.abs(player.vx));
+ if (hop) ctrl.setTrigger(entity, 'hop');
+
+ // While the Hop state plays its clip, code adds the vertical arc.
+ // The arc and the clip share one duration, so touchdown lands on the
+ // same frame the exit-time transition returns the machine to Idle.
+ if (animator.currentState === 'Hop') {
+ player.hopTime = Math.min(player.hopTime + time.delta, HOP_DURATION);
+ transform.position.y = BASE_Y + HOP_HEIGHT * Math.sin((player.hopTime / HOP_DURATION) * Math.PI);
+ } else {
+ player.hopTime = 0;
+ transform.position.y = BASE_Y;
+ }
+ }
+ },
+ { name: 'ControlSystem' },
+);
diff --git a/examples/sprite-animation/src/systems/puffs.ts b/examples/sprite-animation/src/systems/puffs.ts
new file mode 100644
index 000000000..db18b13bc
--- /dev/null
+++ b/examples/sprite-animation/src/systems/puffs.ts
@@ -0,0 +1,47 @@
+import {
+ defineSystem, Query, Mut, Res, Time, Commands,
+ Transform, Sprite,
+} from 'esengine';
+import { Player, Puff, footsteps } from '../components';
+import { PUFF_LIFE } from '../config';
+
+// Turns queued footstep frame events into dust puffs at the player's feet,
+// then fades/raises live puffs and despawns the spent ones. Spawning happens
+// here (not in the event listener) so it runs through Commands, outside the
+// animation system's update.
+export const puffSystem = defineSystem(
+ [Query(Transform, Player), Query(Mut(Transform), Mut(Sprite), Mut(Puff)), Res(Time), Commands()],
+ (players, puffs, time, cmds) => {
+ if (footsteps.pending > 0) {
+ for (const [, transform, player] of players) {
+ for (let i = footsteps.pending; i > 0; i--) {
+ const behind = player.vx >= 0 ? -1 : 1;
+ cmds.spawn()
+ .insert(Transform, {
+ position: {
+ x: transform.position.x + behind * (10 + Math.random() * 8),
+ y: transform.position.y - 44,
+ z: 0,
+ },
+ })
+ .insert(Sprite, {
+ size: { x: 12, y: 7 },
+ color: { r: 1, g: 1, b: 1, a: 0.4 },
+ layer: 3,
+ })
+ .insert(Puff, { life: PUFF_LIFE });
+ }
+ }
+ footsteps.pending = 0;
+ }
+
+ for (const [entity, transform, sprite, puff] of puffs) {
+ puff.life -= time.delta;
+ const t = Math.max(0, puff.life / PUFF_LIFE);
+ sprite.color.a = 0.4 * t;
+ transform.position.y += 26 * time.delta;
+ if (puff.life <= 0) cmds.despawn(entity);
+ }
+ },
+ { name: 'PuffSystem' },
+);
diff --git a/examples/sprite-animation/src/systems/setup.ts b/examples/sprite-animation/src/systems/setup.ts
new file mode 100644
index 000000000..c1323d4f3
--- /dev/null
+++ b/examples/sprite-animation/src/systems/setup.ts
@@ -0,0 +1,104 @@
+import {
+ defineSystem, Res,
+ AnimatorController, AnimatorControllerApi, type AnimatorControllerDef,
+ SpriteAnimation, SpriteAnimationApi,
+} from 'esengine';
+import {
+ CLIP_IDLE, CLIP_WALK, CLIP_HOP, CONTROLLER,
+ MOVE_ENTER, MOVE_EXIT, RUN_BLEND_AT,
+} from '../config';
+import { footsteps } from '../components';
+
+// The character's state machine (Unity Animator model): a float `speed`
+// parameter drives Idle↔Move, Move is a 1D blend that re-selects its clip as
+// `speed` crosses a threshold (same walk clip, faster playback = run), and a
+// `hop` trigger fires a non-looping clip whose end (exit time) auto-returns
+// to Idle. The scene's Animator component references this by name.
+const alienController: AnimatorControllerDef = {
+ parameters: [
+ { name: 'speed', type: 'float', default: 0 },
+ { name: 'hop', type: 'trigger' },
+ ],
+ initialState: 'Idle',
+ states: [
+ {
+ name: 'Idle',
+ clip: CLIP_IDLE,
+ transitions: [
+ { to: 'Move', conditions: [{ param: 'speed', op: 'gt', value: MOVE_ENTER }] },
+ { to: 'Hop', conditions: [{ param: 'hop', op: 'trigger' }] },
+ ],
+ },
+ {
+ name: 'Move',
+ blend: {
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, clip: CLIP_WALK, speed: 1.0 },
+ { value: RUN_BLEND_AT, clip: CLIP_WALK, speed: 1.9 },
+ ],
+ },
+ transitions: [
+ { to: 'Idle', conditions: [{ param: 'speed', op: 'lt', value: MOVE_EXIT }] },
+ { to: 'Hop', conditions: [{ param: 'hop', op: 'trigger' }] },
+ ],
+ },
+ {
+ name: 'Hop',
+ clip: CLIP_HOP,
+ loop: false,
+ // No conditions + exit time = advance when the clip finishes.
+ transitions: [{ to: 'Idle', conditions: [], hasExitTime: true }],
+ },
+ ],
+};
+
+// One-time wiring that needs no assets: the controller (pure data) and the
+// footstep listener (inert until events are attached below).
+export const setupSystem = defineSystem(
+ [Res(AnimatorController), Res(SpriteAnimation)],
+ (ctrl: AnimatorControllerApi, anim: SpriteAnimationApi) => {
+ ctrl.registerController(CONTROLLER, alienController);
+ anim.onEventGlobal((event) => {
+ if (event.name === 'footstep') footsteps.pending++;
+ });
+ },
+ { name: 'SetupSystem' },
+);
+
+// Clip-dependent wiring. The scene preload streams .esanim clips in without
+// blocking startup, so this retries each frame until both asset clips are
+// registered, then arms once: builds the hop clip out of frames the asset
+// clips already loaded (the second clip-authoring path — a code-registered
+// SpriteAnimClip) and attaches the walk clip's footstep frame events.
+let clipsWired = false;
+export const wireClipsSystem = defineSystem(
+ [Res(SpriteAnimation)],
+ (anim: SpriteAnimationApi) => {
+ if (clipsWired) return;
+ const idle = anim.getClip(CLIP_IDLE);
+ const walk = anim.getClip(CLIP_WALK);
+ if (!idle || !walk) return; // still streaming in
+ clipsWired = true;
+
+ anim.registerClip({
+ name: CLIP_HOP,
+ fps: 10,
+ loop: false,
+ frames: [
+ { texture: idle.frames[3].texture, duration: 0.08 },
+ { texture: walk.frames[1].texture, duration: 0.10 },
+ { texture: walk.frames[3].texture, duration: 0.16 },
+ { texture: idle.frames[0].texture, duration: 0.10 },
+ ],
+ });
+
+ // The walk clip's contact frames announce a footstep; puffSystem turns
+ // each one into a dust puff at the player's feet.
+ walk.events = [
+ { frame: 1, name: 'footstep' },
+ { frame: 3, name: 'footstep' },
+ ];
+ },
+ { name: 'WireClipsSystem' },
+);
diff --git a/examples/sprite-animation/src/systems/switch.ts b/examples/sprite-animation/src/systems/switch.ts
deleted file mode 100644
index 423f2b95a..000000000
--- a/examples/sprite-animation/src/systems/switch.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import {
- defineSystem, Query, Mut, Res, Time, SpriteAnimator,
-} from 'esengine';
-import { AnimSwitcher } from '../components';
-
-export const switchSystem = defineSystem(
- [Query(Mut(SpriteAnimator), Mut(AnimSwitcher)), Res(Time)],
- (query, time) => {
- for (const [_entity, animator, switcher] of query) {
- switcher.switchTimer -= time.delta;
- if (switcher.switchTimer <= 0) {
- switcher.isWalking = !switcher.isWalking;
- animator.clip = switcher.isWalking
- ? switcher.walkClip
- : switcher.idleClip;
- animator.currentFrame = 0;
- animator.frameTimer = 0;
- switcher.switchTimer = 2 + Math.random() * 2;
- }
- }
- },
- { name: 'SwitchSystem' }
-);
diff --git a/examples/sprite-animation/thumbnail.png b/examples/sprite-animation/thumbnail.png
index ca0e53542..82be8590f 100644
Binary files a/examples/sprite-animation/thumbnail.png and b/examples/sprite-animation/thumbnail.png differ