-
-
Notifications
You must be signed in to change notification settings - Fork 660
Adding and maintaining your game objects
To make a Renderable participate in the game loop (update and draw), add it to the game world:
app.world.addChild(mySprite);Or from within a Stage:
class PlayScreen extends Stage {
onResetEvent(app) {
app.world.addChild(new Player(100, 200));
app.world.addChild(new HUD(), 10); // z-index 10
}
}melonJS sorts objects by their z property. Lower values are drawn first (behind), higher values are drawn last (in front).
You can set z-index in two ways:
// set via the pos.z property
const sprite = new Sprite(0, 0, { image: "player" });
sprite.pos.z = 5;
app.world.addChild(sprite);
// or pass it as the second argument to addChild
app.world.addChild(sprite, 5);You can change pos.z at any time during gameplay to adjust draw order dynamically.
// deferred removal (safe to call during update)
app.world.removeChild(mySprite);
// immediate removal
app.world.removeChildNow(mySprite);
// remove with keepalive (don't destroy — useful for reuse)
app.world.removeChild(mySprite, true);When melonJS changes state (e.g., from PLAY to GAMEOVER), the world container is reset. All objects are removed unless they have isPersistent set to true:
myHUD.isPersistent = true;The object pool recycles objects to reduce garbage collection pressure. Instead of creating and destroying objects, they're returned to a pool and reused.
Register your class once (e.g., in your game setup):
import { pool } from "melonjs";
pool.register("bullet", BulletEntity, true);The third argument true enables recycling. Your class must implement onResetEvent() to reinitialize state when pulled from the pool.
// pull from pool (creates new or reuses recycled)
const bullet = pool.pull("bullet", this.pos.x, this.pos.y);
app.world.addChild(bullet);
// when done, remove it — it goes back to the pool
app.world.removeChild(bullet);Classes registered with pool.register() are automatically available as Tiled object factories. Objects placed in a Tiled map with a matching class or name will be instantiated using the registered constructor.
For an object to be properly recycled, it must implement onResetEvent():
class BulletEntity extends Sprite {
onResetEvent(x, y) {
this.pos.set(x, y);
this.alive = true;
this.body.setMaxVelocity(10, 0);
}
}