Skip to content

Adding and maintaining your game objects

Aaron McLeod edited this page Nov 5, 2013 · 14 revisions

As you create and work with various renderable objects, you need to tell MelonJS that they need to be executed as part of the game loop. You can do this one of two ways.

Since version 0.9.9, MelonJS provides an ObjectContainer class, as well as an instance of it at me.game.world. You can add your game objects to it via:

me.game.world.addChild(new MySprite());

The legacy style of doing it is (required for 0.9.8 and older):

me.game.add(new MySprite());
me.game.sort();

The ObjectContainer handles the sorting for you, and if you're in 0.9.9 or higher, so will the legacy style. It is advised when using an older version to call all your add statements first, then call sort.

You also need to tell MelonJS the draw order. By default, MelonJS uses the z property on your objects to sort. The lower the number gets updated & painted first, the highest number gets updated & painted last. You can tell MelonJS the draw order one of two ways.

First, declare it in your object definitions:

var MySprite = me.SpriteObject.extend({
    init : function() {
        this.parent(0, 0, me.loader.getImage('sprite'), 64, 64);
        this.z = 2;
    }
});

The second way is by using me.game.add and passing the z-index as the second parameter:

me.game.add(new MySprite(), 2);

This effectively accomplishes the same thing, the latter simply sets the z-index property on the object. You can of course alter the z property on your objects at any time in game. Just be sure to call sort.

Note

It's generally considered a good practice to use defer to ensure that the sort is not called mid loop:

me.game.sort.defer();
Clone this wiki locally