Sprite sheets, atlases and animation state machines for 2D games. Grid sheets and TexturePacker / Aseprite atlases with trimming and pivots, Aseprite tags as clips, per-frame durations, loop, once and ping-pong, chaining (attack → idle), frame events (footsteps, the hit frame of an attack), picking clips from game state by priority, flipping, and animation timing that feels good. Includes teste...
Download skill (.zip) Files on GitHubSprite animation
Drop-in: assets/animator.js (14 tests: frame timing, loops, chained once-clips, events, ping-pong, big dt, flip and rounding,
atlas trims and pivots, Aseprite tags, state priorities; rendered in a browser).
import { gridSheet, atlasSheet, clipsFromAseprite, Animator, animState } from "./core/animator.js";
const sheet = gridSheet(images.hero, 32, 32); // or atlasSheet(img, json) for packed atlases
const anim = new Animator(sheet, {
idle: { frames: [0, 1, 2, 1], fps: 6 },
run: { frames: [8, 9, 10, 11, 12, 13], fps: 12, events: { 1: "step", 4: "step" } },
jump: { frames: [16] }, fall: { frames: [17] },
attack: { frames: [24, 25, 26, 27], fps: 16, loop: false, events: { 2: "hit" }, next: "idle" },
}, { onEvent: (e) => (e === "step" ? sfx("step") : e === "hit" ? player.dealHit() : 0) });
const pick = animState([[(p) => p.attacking, "attack"], [(p) => !p.onGround && p.vy < 0, "jump"], [(p) => !p.onGround, "fall"],
[(p) => Math.abs(p.vx) > 20, "run"], [() => true, "idle"]]);
// update: anim.play(pick(player)); anim.update(dt) draw: anim.draw(ctx, player.x, player.y, { flipX: player.facing < 0 })
Rules
- Advance animations with dt in update; choose frames in draw. Speed can follow movement (
play("run", { speed: |vx| / maxSpeed })). - Gameplay on frames, not timers: the attack’s damage happens on its
hitevent, so animation and hitbox stay in sync. play()of the current clip doesn’t restart it (no stutter); pass{ restart: true }to force.- Pivot at the feet for characters (atlas pivots, or
oy= frame height) so flips and size changes don’t jump. - Draw at rounded positions for pixel art (the animator rounds).
Making the art
- Aseprite: export a sheet + JSON (array, with tags).
clipsFromAsepriteturns tags into clips with real frame durations. - TexturePacker / free packers: “JSON hash” or “array” both work with
atlasSheet; enable trimming to save space. - Common frame counts: idle 2–4, run 6–8, jump 1–2, attack 3–5 (short anticipation, a fast hit frame, longer recovery).
- Placeholder: colored rectangles with 2-frame bobbing still read as “alive” (game-prototyping).
Feel
Squash and stretch on jump and land (game-feel-engineering), a 1-frame white flash on hit, dust particles on footstep events, and hold the hit frame during hit-stop.