melonjs-performance
Qué hace
Explica cómo medir el rendimiento en un juego melonJS y los cambios principales que lo aceleran. Va dirigida a desarrolladores de juegos cuyo juego se atasca o pierde fotogramas.
Cuándo usarla
- ✓Cuando el juego de un desarrollador pierde fotogramas con muchos objetos en pantalla.
- ✓Cuando el juego de un desarrollador tartamudea porque crea muchos objetos en cada fotograma.
- ✓Cuando un desarrollador quiere medir las llamadas de dibujo y el tiempo por fotograma antes de optimizar.
Link de la skill
https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-performance/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Mi juego de melonJS se atasca cuando hay muchos enemigos en pantalla. ¿Cómo puedo acelerarlo?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La skill indica a la IA que active el panel de depuración y lea primero los números, y luego sugiere correcciones como usar un atlas de texturas, agrupar por modo de mezcla y reutilizar objetos.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Performance
Measure first
Register the debug plugin and read the numbers before changing anything:
import { plugin } from "melonjs";
import { DebugPanelPlugin } from "@melonjs/debug-plugin";
await app.init();
plugin.register(DebugPanelPlugin, "debugPanel");
It reports frame time, draw calls, object counts, and can overlay collision shapes and bounds. Draw calls is usually the number that matters.
Batching: the biggest lever
Both GPU backends batch across textures, not just within one: the quad
batcher assigns each source image a texture unit and embeds the unit in the
vertex data, so several different images still flush as a single draw. The pool
is finite — the WebGL batcher gets renderer.maxTextures units (the
maxTextures application setting, "auto" = the device limit capped at 32), the
WebGPU batcher eight per segment. Overflow the pool and the batch flushes.
So the goal is not "one image" but "few state changes". What actually ends a batch:
- Overflowing the texture-unit pool — pack sprites into a
TextureAtlasand prefer one large tileset over several small ones, so a screenful of sprites fits inside the pool with room to spare. - Changing
blendMode—setBlendModeflushes before it touches GL state. Group by blend mode where you can. - Switching batcher — interleaving primitives (
strokeRect,fillRect, debug shapes) or meshes between sprites flushes the quad batcher and rebinds. Draw all the sprites, then all the primitives. - Binding a custom shader — a
ShaderEffecton the quad batcher also turns multi-texture batching off for the duration, dropping you back to one texture per draw.
The advanced blend modes are the expensive ones: overlay, difference,
hard-light, soft-light, color-dodge, color-burn, darken and lighten
cannot be expressed as fixed-function blending, so each such draw is bracketed
on its own — capture the destination, redraw offscreen, composite through a
shader. Right for accents, wrong for hundreds of objects. normal, additive,
multiply, screen and exclusion are plain fixed-function state and cost
nothing extra.
Pooling
Anything spawned frequently — bullets, particles, pickups, damage numbers — should be pooled rather than allocated:
import { createPool } from "melonjs";
const bulletPool = createPool((x, y) => {
const instance = new Bullet(x, y);
return { instance, reset: (x, y) => instance.onResetEvent(x, y) };
});
const b = bulletPool.get(x, y); // recycled: reset(x, y)
// fresh: new Bullet(x, y)
world.removeChild(b); // returns to bulletPool automatically
The container returns a child to whichever pool built it, so removal is enough;
you only call release() yourself for something that was never added to the
world.
me.pool is the older, string-keyed version and is deprecated since
18.0.0. pool.register(name, Class, true) / pool.pull(name) still work and
print a one-off console notice, but a recycled object is no longer returned on
removal, so pooling through it now costs an allocation per spawn. To register a
class so a Tiled map can name it, use registerTiledObjectClass — that is a
separate registry and is not deprecated.
Two rules that cause subtle bugs when missed:
onResetEventmust restore everything the object's lifetime mutates — alpha, tint, scale, animation, velocity. Anything you forget carries into the next use, which looks like a random visual glitch.Pooled objects do not fire
onDestroyEventon removal. Removal always callsonDeactivateEvent, then tries to return the object to the pool that built it; only when nothing owns it does it fall through todestroy(), which is what callsonDestroyEvent. So a successfully recycled object never sees it. Pair event subscriptions withonActivateEvent/onDeactivateEventinstead, or you leak handlers.removeChildis DEFERRED, which breaks a pool you re-lend in the same frame. The removal is queued and runs after the update and draw stack has unwound, so an object you remove and immediately hand out again is torn out from under its new owner when the queue drains: it vanishes, and the frame after that the removal throwsChild is not mine.Take it out immediately instead, keeping the instance alive for reuse:world.removeChildNow(bullet, true); // keepalive: do NOT destro
Preguntas frecuentes
¿Qué debo medir primero?
La skill recomienda el panel de depuración, que muestra el tiempo por fotograma y las llamadas de dibujo.
¿Qué es el agrupado?
El agrupado combina muchos sprites en menos llamadas de dibujo, que suele ser la mayor mejora de velocidad.
¿Por qué cambiar el modo de mezcla ralentiza las cosas?
La skill dice que cambiar el modo de mezcla termina un lote, así que agrupar los sprites por modo de mezcla ayuda.
Detalles
Descripción original del autor
Use 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 plugin, and where the real costs are. Triggers on: performance, slow, frame rate, fps, lag, pool, pool.register, pool.pull, batching, draw calls, InstancedMesh, culling, alwaysUpdate, inViewport, CanvasRenderTarget, optimise, profiling, debug plugin, memory, render targets, hdr.
repo: melonjs/melonJS
Popularidad
- Estrellas en GitHub
- 6,4 mil
- Posición en el ranking
- #14209
- Licencia
- MIT
- Actualizada
- 2/11/2026
Comentarios
- …
Más skills de este repositorio
melonjs-20-migration
6,4 milAyuda a tu agente a escribir código de juegos melonJS para la versión 20 y evitar métodos desactualizados de versiones anteriores, como el arranque asíncrono obligatorio.
melonjs-3d-assets
6,4 milAyuda a tu agente a cargar modelos 3D como archivos glTF, GLB y OBJ en un juego para navegador melonJS, con opciones de escala e iluminación.
melonjs-3d
6,4 milAyuda a tu agente a crear escenas 3D o 2.5D en un juego para navegador melonJS, con cámaras, mallas, luces y profundidad, usando las reglas de ejes del motor.
melonjs-audio
6,4 milAyuda a tu agente a añadir efectos de sonido y música a un juego melonJS, incluida la configuración de audio, las pistas de fondo, el control de volumen y el sonido espacial.
Skills parecidas
diffs
394 milPermite que tu agente genere un diff real y compartible de los cambios, como enlace de visualización o archivo de imagen, en lugar de un resumen escrito a mano.
coding-agent
394 milAyuda a tu agente a pasar un trabajo de programación grande a Codex, Claude Code u OpenCode como trabajador en segundo plano, y después revisar su progreso.
gh-issues
394 milAyuda a tu agente a encontrar incidencias de GitHub, elegir cuáles trabajar y abrir pull requests con correcciones, incluido el seguimiento de los comentarios de revisión.