Skip to main content

Build

Melonjs Sprites and Animation

melonJS

Use this skill when creating sprites, playing frame animations, or working with texture atlases in melonJS. Covers Sprite construction from a plain image or an atlas region, addAnimation/setCurrentAnimation, TextureAtlas for TexturePacker/ShoeBox/Aseprite, tint, flip, NineSliceSprite, and the centred anchorPoint that offsets naive positioning. Triggers on: Sprite, new Sprite, addAnimation, setCurrentAnimation, isCurrentAnimation, onFrame, onComplete, play, pause, flicker, anchorPoint, TextureAtlas, TexturePacker, Aseprite, ShoeBox, atlas, region, framewidth, frameheight, tint, flipX, flipY, NineSliceSprite, animation.

  • New
  • v1.0.4
  • No reviews yet

Capabilities

  • pos is the centre, not the top-left

    Renderable.anchorPoint defaults to (0.5, 0.5), so a sprite's pos is…

  • Constructing a sprite

  • Animation

    Frame indices are into the framewidth/frameheight grid

  • Texture atlases

    Atlases matter for performance: the GPU batchers bind several textures…

Getting started

Full instructions

Install the skill, then ask your AI tool for the task in plain words. The full SKILL.md below shows what it covers.

Instructions: SKILL.mdv1.0.4

Sprites, animation and atlases

Creating sprites from images or atlases, driving frame animation, and the
positioning trap that catches almost everyone.

pos is the centre, not the top-left

Renderable.anchorPoint defaults to (0.5, 0.5), so a sprite's pos is its
centre. Container forces (0, 0) instead, which is why containers and
sprites appear to disagree.

js
// a 64×64 sprite at (100, 100) covers 68..132, not 100..164
const s = new Sprite(100, 100, { image: "hero", framewidth: 64, frameheight: 64 });

s.anchorPoint.set(0, 0);   // switch to top-left positioning if you prefer

// or in the settings, by name: "top-left", "bottom" (the feet), "center",
// "top", "left", "right", "top-right", "bottom-left", "bottom-right"
const hero = new Sprite(x, y, { image: "hero", anchorPoint: "bottom" });

Writing top-left maths against the centred default puts everything half a sprite
off, with no error. It is the most common source of "close but subtly wrong"
placement.

Constructing a sprite

From a plain image:

js
const hero = new Sprite(x, y, {
    image: "hero",          // preloaded asset name
    framewidth: 32,
    frameheight: 32,
});

From a texture atlas region:

js
const atlas = new TextureAtlas(loader.getJSON("sprites"), loader.getImage("sprites"));
const coin = new Sprite(x, y, { image: atlas, region: "coin_01.png" });

framewidth / frameheight define the animation grid on a sheet. Omit them and
the whole image is one frame.

Animation

js
hero.addAnimation("idle", [0, 1, 2, 3], 100);   // frames, ms per frame
hero.addAnimation("walk", [4, 5, 6, 7]);
hero.addAnimation("die",  [8, 9], 150);

hero.setCurrentAnimation("walk");
hero.setCurrentAnimation("die", "idle");                          // chain to idle when it ends
hero.setCurrentAnimation("die", { loop: false });                 // play once, hold the last frame
hero.setCurrentAnimation("die", { loop: false, onComplete: fn }); // …and call fn when it does
hero.setCurrentAnimation("use", { next: "idle", onComplete: fn }); // call fn, then chain to idle
hero.setCurrentAnimation("run", { onFrame: (frame) => {            // each frame playback reaches
    if (frame === 3 || frame === 8) footstep();
} });

if (hero.isCurrentAnimation("walk")) { /* … */ }

Frame indices are into the framewidth/frameheight grid. With an atlas, use
atlas.getAnimationSettings([regionNames]) and spread it into the Sprite
settings, or atlas.createAnimationFromName([regionNames]), which returns a
ready-made Sprite. On a fixed-cell spritesheet only numeric indices are
accepted — passing region names throws.

The second argument to setCurrentAnimation is polymorphic. A string chains
to that animation when this one ends. An options object takes
{ loop, next, speed, onComplete, onFrame }, and only an explicit loop: false
stops the looping. A bare function is the legacy form: it fires at every cycle end,
and only holds the last frame if it returns false. Omit the argument entirely
and the animation loops forever. The options type also has a crossfade, which
only a 3D GLTFModel reads (see melonjs-3d-assets); a sprite ignores it.

onFrame(frame) is called with frame 0 when the animation starts, then with each
frame playback reaches, so a footstep or a hit lands on its frame without polling
getCurrentAnimationFrame(). A long tick reports every frame it goes past. It is
not called for a frame set with setAnimationFrame, nor for the frame 0 a
play-once animation would wrap to. Keep the callback in a field when you call
setCurrentAnimation every frame: re-selecting keeps the first one anyway.

With both next and onComplete, the callback runs first and the chained
animation starts with none of its own, so a one-off action (a pickup, an
attack) needs no manual switch back to idle.

Re-selecting the animation that is already current is a no-op, so calling
setCurrentAnimation every frame is safe, and an isCurrentAnimation check
around it adds nothing. The exception is a loop: false run that has
finished
: selecting it again plays it again, so a death animation selected
every frame replays forever. Select a play-once animation once, on the event
that starts it. An unknown id throws.

A frame can carry its own delay, as { name, delay } in place of the index or
region name: [{ name: 3, delay: 200 }, { name: 4, delay: 100 }].
play(name?, options?) switches and plays (or, with no name, resumes),
pause() freezes the current frame and stop() rewinds to the first one and
pauses there; the options are setCurrentAnimation's.

addAnimation with an id that exists replaces it, which is how you change an
animation's frames or speed (hero.addAnimation("walk", [4, 5, 6, 7], 200)).
Redefining the one that is playing takes effect at once: the playing frame is
kept if the new strip still has it, playback restarts on frame 0 if not, a
finished loop: false run holds the new last frame, and the
setCurrentAnimation options stay. Before 20.13 it kept the old frame count, so
a shorter strip threw on the next update() and a longer one never reached its
new frames.

Since 20.14, a frame the texture does not have (a number past the end of the
sheet, a name the atlas does not hold) is left out with a console warning
naming it, and the frames that exist play in order; addAnimation returns how
many it kept.

Texture atlases

TextureAtlas reads several formats:

source how
TexturePacker / Free Texture Packer JSON, "JSON (Array)" or "JSON (Hash)" new TextureAtlas(loader.getJSON(name), loader.getImage(name))
Aseprite JSON export same as TexturePacker — the format is detected from meta.app
another tool writing either layout (spritesheet.dev, your own exporter) same call. Since 20.18 an unknown meta.app is recognised from the file's structure: meta.frameTags reads as Aseprite, frames with a frame rectangle as TexturePacker. Before, it threw Unknown texture atlas format
Aseprite .aseprite / .ase binary loader type "aseprite", which stores the composited image and a JSON sidecar under the one asset name
ShoeBox JSON export using the melonJS exporter settings file; same call as TexturePacker
fixed-cell spritesheet new TextureAtlas({ framewidth, frameheight, anchorPoint }, loader.getImage(name))
multi-page pass an array of atlas JSON objects as the first argument

Helpers: createSpriteFromName(name), createAnimationFromName([names]),
getAnimationSettings([names]).

Atlases matter for performance: the GPU batchers bind several textures at once
(up to renderer.maxTextures), so a handful of separate images still batch —
but once a frame crosses that many distinct textures the batch has to flush.
Packing into one atlas keeps everything on a single binding.

Visual properties

js
sprite.setTint("#ff8000");   // multiply tint
sprite.alpha = 0.5;
sprite.flipX(true);                   // mirror horizontally
sprite.flipY(true);
sprite.blendMode = "additive";        // see the effects skill for the full list
sprite.scale(2, 2);                   // ← multiplicative, see below
sprite.flicker(1000, function () {    // blink for a second, then…
    this.ancestor.removeChild(this);  // …`this` is the sprite; the flicker has ended
});

A tint multiplies, so it can only darken. It cannot turn a red sprite blue,
or flash it white. For one sprite drawn in several palettes (a team colour, an
elite enemy, a frozen one) use a GradientMapEffect, which redraws it from its
brightness in the colours you list; for a white hit flash, a FlashEffect. Both
are in melonjs-effects-and-shaders.

js
// the same art as a second team
enemy.addPostEffect(new GradientMapEffect(app.renderer, {
    colors: [[0.1, 0.05, 0.3], [0.3, 0.4, 0.9], [0.8, 0.9, 1]],
}));

scale() is multiplicative, not absolute. Calling it every frame compounds.
For absolute scaling reset first:

js
sprite.currentTransform.identity();
sprite.currentTransform.scale(s, s, 1);

This bites hardest with pooled sprites, which arrive carrying their previous
life's transform.

NineSliceSprite

For panels and dialogue boxes that stretch without distorting their corners:

js
new NineSliceSprite(x, y, {
    image: "panel", width: 300, height: 120,
    insetx: 12, insety: 12,     // lowercase x/y — `insetX` is silently ignored
});

width and height are mandatory and the constructor throws without them.
The insets default to a quarter of the frame.

Pooling

Frequently spawned sprites should be pooled:

js
import { createPool } from "melonjs";

const bulletPool = createPool((x, y) => {    // me.pool is deprecated
    const instance = new Bullet(x, y);
    return { instance, reset: (x, y) => instance.onResetEvent(x, y) };
});
const b = bulletPool.get(x, y);             // new Bullet(x, y), or reset(x, y) on a reused one
world.removeChild(b);                       // returns it to bulletPool automatically

Two consequences:

  • A recyclable class's onResetEvent must reset everything its lifetime
    mutates — alpha, tint, scale, animation state. Anything you forget carries
    over to the next use.
  • Pool-recycled objects do not fire onDestroyEvent on removal. Pair event
    subscriptions with onActivateEvent / onDeactivateEvent instead.

Symptom → cause

symptom cause
everything offset by half a sprite top-left maths against the centred anchorPoint
sprite grows every frame scale() is multiplicative — reset the transform
a recycled sprite keeps its old look onResetEvent does not restore every mutated property
event handlers leak on pooled objects bound in the constructor rather than onActivateEvent
animation never advances no framewidth/frameheight, so the sheet is one frame
animation plays once and stops { loop: false }, or a callback that returned false
a loop: false animation keeps replaying setCurrentAnimation called every frame: a finished play-once run is restarted by selecting it again
a one-frame animation never calls its onComplete a looping one-frame animation does not step; play it with loop: false or next (before 20.12 even those never completed)
TypeError reading offset or delay in update() after re-adding the playing animation with fewer frames, or a longer one never shows its new frames before 20.13 redefining the current animation kept its old frame count; upgrade
a console warning addAnimation("walk"): no frame … in the texture, or a TypeError reading delay / offset on an older melonJS a frame number or name the sheet or atlas does not have (often an atlas re-exported without one of its images): fix the frame list or re-export the atlas
this is wrong in a flicker(ms, callback) callback, or a flicker started from it stops at once before 20.13.0 the callback ran on an internal object and the flicker was stopped after it; now this is the sprite and the flicker has already ended
sprites do not batch more distinct textures in one frame than renderer.maxTextures
nine-slice corners stretch anyway insetX/insetY instead of insetx/insety
an atlas animation blinks: the sprite vanishes on some of its frames (before 20.17) the frames the packer stored rotated were drawn off the screen unless the sprite was at (0, 0); a nine-slice sprite from a rotated frame was stretched along the wrong axis. Update; on an older version, turn rotation off in the packer
Unknown texture atlas format: <name or URL> from new TextureAtlas before 20.18, an atlas whose meta.app named a tool the engine did not know, even in the TexturePacker or Aseprite layout (and ShoeBox, matched in lowercase only); since 20.18, a file that is in neither layout: no meta.size, a frame with no frame rectangle, or a list of frames with no filename
frames.forEach is not a function from new TextureAtlas before 20.18, a TexturePacker "JSON (Hash)" export; re-export as "JSON (Array)" or update
a frame of an Aseprite JSON export is not found by its name exported as "Array": the frames are then named by their position ("0", "1"…); export as "Hash" to keep the names
a tint will not turn the sprite the colour asked for, only a darker one a tint multiplies the art's own colours: recolour with a GradientMapEffect, flash with a FlashEffect
  • melonjs-renderables — anchors, draw order, custom draw
  • melonjs-getting-started — preloading images and atlases

Explore more skills

Browse all
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

More from melonJS

View source →
melonjs-renderablesUse this skill when subclassing Renderable, writing a custom draw() method, handling pointer or click events on game objects, applying post effects and shaders, or controlling draw order. Covers the pos-relative draw contract, isKinematic…0 installsmelonjs-testingUse this skill to check that a melonJS game actually works before saying it does: running it in a headless browser, reading the console the engine writes, finding out which renderer the run got, driving the keyboard and the pointer,…0 installsmelonjs-ui-and-textUse this skill for HUDs, buttons, menus, options screens, dialogue panels, progress bars and on-screen text in melonJS. Covers UIBaseElement/UISpriteElement/UITextButton, UICheckbox, UISlider, ProgressBar, UIPanel (skins, layout,…0 installsmelonjs-inputUse this skill for keyboard, pointer, mouse, touch and gamepad input in melonJS. Covers the bindKey action indirection, registerPointerEvent on regions, the isKinematic requirement that silently blocks pointer events, which of several…0 installsmelonjs-performanceUse this skill when a melonJS game drops frames, allocates heavily, or needs to scale to many objects. Covers object pooling, draw-call batching, atlases, baking with CanvasRenderTarget, instancing, culling and alwaysUpdate, the debug…0 installsmelonjs-deploymentUse this skill when packaging, shipping or scaffolding a melonJS game — starting a project with create-melonjs, building for the web, browser support and transpiling, and bundle size. For running inside a game portal, a native app, a…0 installs

Frequently asked questions about melonjs-sprites-and-animation

What does the melonjs-sprites-and-animation skill do?

Use this skill when creating sprites, playing frame animations, or working with texture atlases in melonJS. Covers Sprite construction from a plain image or an atlas region, addAnimation/setCurrentAnimation, TextureAtlas for TexturePacker/ShoeBox/Aseprite, tint, flip, NineSliceSprite, and the centred anchorPoint that offsets naive positioning. Triggers on: Sprite, new Sprite, addAnimation, setCurrentAnimation, isCurrentAnimation, onFrame, onComplete, play, pause, flicker, anchorPoint, TextureAtlas, TexturePacker, Aseprite, ShoeBox, atlas, region, framewidth, frameheight, tint, flipX, flipY, NineSliceSprite, animation. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the melonjs-sprites-and-animation skill?

Run `npx @skills-hub-ai/cli install melonjs-sprites-and-animation` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/melonjs-sprites-and-animation/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does melonjs-sprites-and-animation work with?

melonjs-sprites-and-animation runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the melonjs-sprites-and-animation skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use melonjs-sprites-and-animation after installing it?

In Claude Code, type `/melonjs-sprites-and-animation` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the melonjs-sprites-and-animation skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.

Badge for your README

Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/melonjs-sprites-and-animation)](https://skills-hub.ai/skills/melonjs-sprites-and-animation)
HTML
<a href="https://skills-hub.ai/skills/melonjs-sprites-and-animation"><img src="https://skills-hub.ai/api/badges/skill/melonjs-sprites-and-animation" alt="Install on Skills Hub"></a>

More options in the badge docs.