Skip to content

MelonJS Core

Aaron McLeod edited this page Nov 4, 2013 · 17 revisions

MelonJS currently operates quite similar to that of most game frameworks. It manages the game loop for you, giving you update & draw/paint calls to work with.

MelonJS provides various named states to work with, in conjunction with ScreenObjects to better manage different views and controls for the game.

The states are:

name index
LOADING 0
MENU 1
READY 2
PLAY 3
GAMEOVER 4
GAME_END 5
SCORE 6
CREDITS 7
SETTINGS 8

You can define if your own states as well.

MelonJS provides resource management to make it easy to load various images, sounds, etc.

There is also Tiled Map integration with MelonJS, the details on how to use are in the tutorial.

Framework Workflow

When you initialize melonjs via me.video.init, it sets up the camera, the world object (an instance of me.ObjectContainer), and the game loop.

Since MelonJS is an HTML5 & Canvas based framework, the engine depends on the requestAnimationFrame function that modern browsers provide. Mozilla Developer Network covers the details on the function pretty well, but the short of it is that the requestAnimationFrame tries to run at 60 frames per second. It accepts a function to execute each time a frame runs. So with melon, we tell it to update the game objects as we have defined and to execute all the draw calls.

The requestAnimationFrame is utilized to call two main operations: update & draw.

The update function invokes the update on the me.game.world object, which is an ObjectContainer. The update function of the container loops through each of its child objects. If the child object is another container, then that container will invoke all its children's update function.

The update function goes through a couple checks before updating the object iself.

  1. Will pass the update if the game state is set to paused, and the object is not set to update when paused.
  2. The object must be either in viewport, floating or set to alwaysUpdate.

Note that no delta time is passed to the update call. If you need to know the time change from the last frame, store a time object somewhere, and calculate the difference like so:

init : function() {
    this.lastTime = me.timer.getTime();
},
update : function() {
    var d = this.lastTime - me.timer.getTime();
    this.lastTime = me.timer.getTime();
}

Once all updates are complete, the draw cycle begins. The draw checks against the objects in the same way. Ensures the game is not paused, and that the object is either in view or set to always update. It also checks if the object has isRenderable set to true. There may be some objects you want to have update in the game loop, but not draw anything.

Details

To learn more about the object types explained here, check out:

Clone this wiki locally