-
-
Notifications
You must be signed in to change notification settings - Fork 657
MelonJS Core
melonJS manages the game loop for you, giving you update and draw calls to work with. The entry point is the Application class, which initializes the renderer, creates the game world and viewport, and starts the game loop.
melonJS provides named states to manage different views (menu, gameplay, game over, etc.), used in conjunction with Stage:
| name | index |
|---|---|
| LOADING | 0 |
| MENU | 1 |
| READY | 2 |
| PLAY | 3 |
| GAMEOVER | 4 |
| GAME_END | 5 |
| SCORE | 6 |
| CREDITS | 7 |
| SETTINGS | 8 |
You can define custom states as well. Each state is associated with a Stage instance:
import { state, Stage } from "melonjs";
class PlayScreen extends Stage {
onResetEvent(app) {
// called when this state becomes active
// app is the Application instance
}
onDestroyEvent(app) {
// called when leaving this state
}
}
state.set(state.PLAY, new PlayScreen());
state.change(state.PLAY);melonJS provides resource management to load images, sounds, maps, and other assets. See the Resources page for details.
There is near-complete Tiled Map Editor integration built into melonJS. See the tutorial and the Tiled collision shapes guide.
When you create an Application, it sets up the viewport, the world container (an instance of World), and the game loop.
import { Application } from "melonjs";
const app = new Application(800, 600, {
parent: "screen",
scale: "auto",
});The game loop uses requestAnimationFrame to run at up to 60fps. Each frame executes two phases: update and draw.
The update function is called on app.world, which is a Container. The container loops through each child, calling their update(dt) method. If a child is another container, it recursively updates its children.
Before updating a child, the container checks:
- If the game is paused and the object is not set to update when paused, the update is skipped.
- The object must be in the viewport, floating, or set to
alwaysUpdate.
The dt parameter is the delta time (milliseconds) since the last frame. The update method should return true if the object needs to be redrawn, or false to skip drawing. Only return true when necessary (e.g., when the object is moving or animating) — this is a key performance optimization.
Once all updates are complete, the draw cycle begins only if at least one update returned true. If all updates return false, drawing is skipped entirely for that frame.
For each child that needs drawing, the container calls:
-
preDraw(renderer)— prepares the rendering context (save state, apply transforms, tint, blend mode) -
draw(renderer)— draws the renderable -
postDraw(renderer)— restores the context
All draw operations in draw() are relative to the position and transforms applied by preDraw(). If you override draw(), draw at (0, 0) — the transforms handle positioning.