/melonjs:melonjs-eventsfrom melonjs
Covers the melonJS event bus and lifecycle hooks — subscribing to engine events, per-frame and per-state event names, renderable lifecycle callbacks, and unsubscribing without leaking.
Ships in melonjs. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
import { event } from "melonjs";
const onUpdate = () => { /* … */ };
const unsubscribe = event.on(event.GAME_UPDATE, onUpdate); // on() returns its own off()
event.once(event.LEVEL_LOADED, () => { /* … */ });
// two ways to undo it — the same reference, or the returned function
event.off(event.GAME_UPDATE, onUpdate);
unsubscribe();
event.on/once/off/has all take an optional third context argument,
invoked as the handler's this. off matches on the pair — handler identity
AND context identity. on(EVT, fn, this) followed by off(EVT, fn) removes
nothing, silently.
Store the handler reference, or use the context argument. An inline arrow or
a fresh .bind(this) in the on call can never be removed — that is the
standard way to leak listeners in melonJS.
// ✗ unremovable
event.on(event.GAME_UPDATE, this.tick.bind(this));
// ✓ keep the bound reference
this._tick = this.tick.bind(this);
event.on(event.GAME_UPDATE, this._tick);
// later: event.off(event.GAME_UPDATE, this._tick);
// ✓ or skip the bind entirely — the context is part of the identity
event.on(event.GAME_UPDATE, this.tick, this);
// later: event.off(event.GAME_UPDATE, this.tick, this);
Custom event names work at runtime (event.emit("my.custom.event", payload)),
but on/emit are typed against a closed map of the engine's own events, so in
TypeScript a name outside that map is a compile error. Use your own emitter for
game events in a .ts project.
Per frame
| event | when |
|---|---|
GAME_BEFORE_UPDATE / GAME_UPDATE / GAME_AFTER_UPDATE | around the world update — GAME_UPDATE is not emitted while paused |
GAME_BEFORE_DRAW / GAME_AFTER_DRAW | around the draw pass, on frames that redraw: one where no update reported a change is not drawn |
WORLD_STEP | after the physics step |
TICK | the raw engine tick |
Lifecycle
| event | when |
|---|---|
BOOT, GAME_INIT, VIDEO_INIT | engine start-up |
STATE_CHANGE, STATE_PAUSE, STATE_RESUME, STATE_STOP | state machine |
STAGE_RESET | a stage was reset |
LEVEL_LOADED | a Tiled level finished loading |
LOADER_PROGRESS, LOADER_COMPLETE, LOADER_ERROR | asset loading: every loader.preload(), and a bundle loaded with loader.load(id) (20.14); not one asset loaded with loader.load(descriptor) |
BLUR / FOCUS | the page lost or regained focus |
CANVAS_ONRESIZE, VIEWPORT_ONRESIZE | relayout hooks |
POINTERMOVE | global pointer movement |
Use LOADER_PROGRESS / LOADER_COMPLETE. The loader.onProgress /
loader.onload / loader.onError properties were deprecated in 18.2.0 and
removed in 20.3: they were module-level let bindings on an ES module
namespace, so loader.onProgress = fn threw and the documented migration path
never worked. For completion, loader.preload(assets, onloadcb) also takes the
callback directly.
Prefer these over bus subscriptions where they fit — the engine calls them at the right times and there is nothing to unsubscribe:
| callback | when |
|---|---|
onActivateEvent() | addChild-ed into a container that is already attached to the world root (a Container forwards it to its children) |
onDeactivateEvent() | removed from its container — including the automatic world clear on a state change. Once per onActivateEvent: the children of a removed container, at any depth, are told once |
onDestroyEvent() | destroy() ran; called with no arguments from the container-removal path |
onCollisionStart / onCollisionActive / onCollisionEnd | contacts |
Note the activate gate: adding a child to a detached container fires nothing.
The callback arrives later, when that container itself is added to the world.
And an isPersistent renderable survives the world clear between stages, so it
gets no fresh onActivateEvent on the next state.
Pair subscriptions with activate/deactivate, not the constructor. This is the rule that keeps pooled objects working:
onActivateEvent() {
this._tick = this.update.bind(this);
event.on(event.GAME_UPDATE, this._tick);
input.registerPointerEvent("pointerdown", this, this._onDown);
}
onDeactivateEvent() {
event.off(event.GAME_UPDATE, this._tick);
input.releasePointerEvent("pointerdown", this);
}
Pool-recycled objects never fire onDestroyEvent on removal — removeChildNow
first tries to return the child to the pool that built it, and only calls
destroy() when nothing owns it. So anything taken from a createPool goes
back to that pool instead. Anything you clean up there will not run. destroy() is also what calls
releaseAllPointerEvents(this), which is why a pooled object must release its
own pointer registrations in onDeactivateEvent.
Events can arrive while a stage is being dismantled, when the current state is already something else:
if (!state.isCurrent(state.PLAY)) return;
Without this, a "children emptied" handler can reset the wrong stage.
Contact callbacks fire inline inside the physics step, mid-iteration over the
detector's pair list. container.removeChild() is safe there — it defers the
actual removal to the next tick, which is exactly why it defers. The immediate
forms are the dangerous ones: removeChildNow() tears the object down under
the iteration, via the internal destroy() it calls, which nulls pos and
body. (destroy() is engine teardown and is not in the published types, so
removeChildNow is the call a game actually makes.) The builtin
detector guards the pair it is currently resolving, but nothing guarantees that
for the rest of the step or for another adapter.
Use removeChild(), or flag the work and drain it from Stage.update.
| symptom | cause |
|---|---|
| handler still fires after removing the object | event.off given a different function reference, or a different context than on got |
| handlers accumulate on pooled objects | subscribed in the constructor rather than onActivateEvent |
| cleanup never runs on a pooled object | pooled removal does not fire onDestroyEvent |
| crash during a stage switch | callback ran mid-teardown — guard with state.isCurrent |
| crash after a collision | removeChildNow() inside a contact callback — use removeChild() |
| progress callbacks never fire | assigned loader.onProgress (removed in 20.3) instead of subscribing to LOADER_PROGRESS |
a LOADER_COMPLETE handler (a state.change to the first screen) runs again mid-game | a later preload(), or a level's bundle loaded with loader.load(id), emits it too; subscribe with event.once, or use preload()'s promise or callback |
onActivateEvent never runs | the child was added to a container not yet attached to the world |
onDeactivateEvent runs twice when a group is removed (a count goes negative, a light or listener is released twice) | the group's onDeactivateEvent and its destroy() both reached the children, before 20.13.0 — now once per onActivateEvent |
onDeactivateEvent never runs on a child of a group built off-world and destroyed | it never had onActivateEvent either: the pair is only sent to children that entered the world |
melonjs-scenes-and-state — the state machine and stage lifecyclemelonjs-performance — pooling, and why activate/deactivate pairing mattersWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub melonjs/melonjs --plugin melonjs27 skills in this plugin
/melonjsUse this skill FIRST for any melonJS task, and when asked to build a game for the browser with no engine named; it says what melonJS is the right engine for, turns a game idea into a plan, and routes to the right specialised skill. melonJS is an open-source 2D, 2.5D and 3D HTML5 game engine running on WebGPU, WebGL 2 or Canvas, with no runtime dependencies. Covers Application setup, the scene graph, renderables, sprites, tilemaps, physics, audio, particles, shaders, and the 3D tier — perspective cameras, meshes and glTF scenes. Triggers on: melonjs, melonJS, me.game, Application, app.init, app.world, Renderable, Sprite, Stage, state.change, Camera2d, Camera3d, Mesh, tilemap, Tiled, TMX, ParticleEmitter, ShaderEffect, make a game, build a game, browser game, web game, HTML5 game, HTML5 game engine, JavaScript game, TypeScript game, 2D game, platformer, top-down game, puzzle game, shooter, arcade game, game jam, playable ad, which game engine./melonjs-20-migrationUse this skill when writing melonJS code that may be based on pre-20.x knowledge, when migrating a game from melonJS 19.x or earlier, or when an API you expected does not exist. Covers the mandatory async Application.init(), the WebGL 2 baseline and WebGPU backend, renderable post effects replacing the shader property, the deprecated exports still present, and what changed again during 20.x. Triggers on: migration, upgrade, melonJS 19, me.game, me.video.init, video.renderer, renderable.shader, Compositor, CanvasTexture, me.Math, pool.pull, pool.register, world.adapter, uvOffset, deprecated./melonjs-3dUse this skill for anything 3D or 2.5D in melonJS — Camera3d, Mesh, InstancedMesh, Sprite3d billboards, Light3d, ground shadows, glTF/GLB scenes, and depth sorting. Covers the Y-down/+Z-forward convention (OpenGL's inverse), the cameraClass opt-in, orthographic (isometric) projection, clip planes, and the Canvas fallback's limits. Triggers on: Camera3d, toon, cel shading, toonBands, outlineWidth, outlineMode, rimLight, orthographic, isometric, orthoHeight, orthoWidth, projection, Mesh, InstancedMesh, Sprite3d, Trail3d, Light3d, billboard, glTF, glb, 3D, 2.5D, depth, cameraClass, fov, setClipPlanes, setFog, fog, heightFalloff, transparent, transparency, blendMode, castGroundShadow, shadowGroundPoint, lit, emissive, specular, shininess, normalMap, alphaCutoff, depthTest, vertexColors, worldToScreen, screenToRay, screenToWorld, pick, pickable, Ray3d, intersectRay, hit3d, followOffset, setBasis, getBasis, lookAt, orbit, up vector, gimbal, slerp, turn a direction, physics, rapier3d, Capsule3d, TriangleMesh3d./melonjs-3d-assetsUse this skill when loading 3D models into melonJS — glTF and GLB scenes, OBJ/MTL models, materials, imported lights, node animation, skinned characters, crossfades and attachments, ground shadows and GPU instancing. Covers level.load options including the async flag, the rightHanded conversion, and exactly what the loader does and does not support. Triggers on: glTF, gltf, glb, OBJ, MTL, 3D model, getGLTF, getOBJ, getMTL, GLTFModel, GLTFScene, level.load glb, rightHanded, lightIntensityScale, castGroundShadow, shadowGroundY, EXT_mesh_gpu_instancing, KHR_lights_punctual, alphaMode, doubleSided, map_d, map_bump, normalize, animationspeed, skinning, skinned mesh, skin, JOINTS_0, WEIGHTS_0, rigged character, Mixamo, crossfade, blend animations, reverseAnimation, setAnimationTime, play backwards, attach to bone, addChildToNode, getNodeTransform, getNodeNames, Blender export, 3D asset./melonjs-audioUse this skill for sound and music in melonJS — loading audio, playing effects, background tracks, audio sprites, volume and muting, spatial audio, procedural tone/noise generation, and effects such as reverb or a compressor on the whole mix. Covers the mandatory audio.init format list, the directory-not-file src convention, playTrack versus play, the fixed listener and pixel-scale distances of positional sound, and browser autoplay unlocking. Triggers on: audio, sound, audio.init, audio.play, playTrack, stopTrack, audio.load, sfx, music, volume, mute, fade, rate, pitch, sprite audio, stereo, panner, position, listener, refDistance, reverb, echo, delay, compressor, distortion, filter, audio effect, audio.tone, audio.noise, getAudioContext, getMasterGain, hasAudio, hasFormat, autoplay, no sound, sound stopped working, context suspended, silent after idle, clips silent but tones play./melonjs-camera-and-drawingUse this skill for camera control and immediate-mode drawing in melonJS — following a target, viewport bounds, shake and fade, secondary cameras and what each one draws, and drawing shapes, lines and gradients inside a custom draw(). Covers world versus screen coordinate conversion, clipping and masking, baking with CanvasRenderTarget, and reading pixels back. Triggers on: Camera2d, viewport, follow, offset, look ahead, setBounds, minimap, second camera, split screen, cullMask, visibilityLayer, hide from a camera, zoom, roll, shake, fadeIn, fadeOut, CameraEffect, addCameraEffect, MaskEffect, iris, image mask, PixelateTransitionEffect, worldToLocal, localToWorld, worldToScreen, screenToRay, screenToWorld, colorMatrix, renderer.fill, renderer.stroke, setGlobalAlpha, fillArc, Rect, Ellipse, Polygon, Line, Path2D, SVG path, Gradient, clipRect, mask, CanvasRenderTarget, NoiseTexture2d, lookAt, setBasis, orbit, toImageData, getImageData, toBlob, toDataURL, screenshot, read pixels.Other plugins' skills for the same job