Skip to content

Container

Olivier Biot edited this page Apr 5, 2026 · 2 revisions

The Container

All visual objects in melonJS live inside a Container — a scene graph node that manages child renderables and calls their update() and draw() methods as part of the game loop.

The root container is the World (app.world), an instance of the World class which extends Container. Every object you add to the game goes into this tree:

app.world.addChild(mySprite);
app.world.addChild(myContainer);

Key Features

  • Automatic sorting — children are sorted by their z property (draw order). Lower z values are drawn first (behind), higher values drawn last (in front).
  • Nested containers — containers can hold other containers, creating a hierarchy. Transforms (position, rotation, scale) cascade from parent to child.
  • Update/draw gating — the container skips updating or drawing children that are off-screen, paused, or not renderable.
  • Clipping — set container.clipping = true to clip children to the container's bounds.
  • Child bounds — set container.enableChildBoundsUpdate = true to automatically compute bounds from children (expensive, use sparingly).

Default Dimensions

When no width/height is specified, a Container defaults to Infinity — meaning no intrinsic size and no clipping. The container acts as a pure grouping/transform node. Its anchorPoint is always (0, 0) — children position from the container's top-left origin.

import { Container, Sprite } from "melonjs";

// a group with no explicit size
const group = new Container();
group.pos.set(100, 100);
group.addChild(new Sprite(0, 0, { image: "item1" }));
group.addChild(new Sprite(32, 0, { image: "item2" }));

app.world.addChild(group);

Update & Draw Conditions

Before processing a child's update/draw, the container checks:

  1. If the game is paused and the object is not set to update when paused, it is skipped.
  2. The object must be in the viewport, floating, or set to alwaysUpdate.

Accessing the Application

Any renderable in the container tree can access the Application instance via this.parentApp:

class MyObject extends Renderable {
    onActivateEvent() {
        const viewport = this.parentApp.viewport;
        const renderer = this.parentApp.renderer;
    }
}

Clone this wiki locally