melonJS
    Preparing search index...

    Class World

    an object representing the physic world, and responsible for managing and updating all children and physics

    Hierarchy (View Summary)

    Index

    Constructors

    • Parameters

      • Optionalx: number = 0

        position of the container (accessible via the inherited pos.x property)

      • Optionaly: number = 0

        position of the container (accessible via the inherited pos.y property)

      • Optionalwidth: number = Infinity

        width of the world container

      • Optionalheight: number = Infinity

        height of the world container

      • Optionaladapter: PhysicsAdapter = undefined

        physics adapter to use; defaults to a new BuiltinAdapter instance

      Returns World

    Properties

    _comparator: {}
    _sortOn: string

    The property of the child object that should be used to sort on this container value : "x", "y", "z"

    "z"
    

    the physics adapter driving this world. Defaults to a BuiltinAdapter wrapping the engine's native SAT-based physics. Override at Application construction time via settings.physic.adapter. Cannot be swapped at runtime.

    alpha: number

    Define the renderable opacity
    Set to zero if you do not wish an object to be drawn

    • Renderable#setOpacity
    • Renderable#getOpacity
    1.0
    
    alwaysUpdate: boolean

    Whether the renderable object will always update, even when outside of the viewport

    false
    
    ancestor: Container | Entity

    a reference to the parent object that contains this renderable

    undefined
    
    anchorPoint: ObservablePoint

    The anchor point is used for attachment behavior, and/or when applying transformations.
    The coordinate system places the origin at the top left corner of the frame (0, 0) and (1, 1) means the bottom-right corner

    a Renderable's anchor point defaults to (0.5,0.5), which corresponds to the center position.

    Note: Object created through Tiled will have their anchorPoint set to (0, 0) to match Tiled Level editor implementation. To specify a value through Tiled, use a json expression like json:{"x":0.5,"y":0.5}.

    <0.5,0.5>
    

    the application (game) this physic world belong to

    autoDepth: boolean

    Specify if the children z index should automatically be managed by the parent container

    true
    
    autoSort: boolean

    Specify if the children list should be automatically sorted when adding a new child

    true
    
    autoTransform: boolean

    When enabled, an object container will automatically apply any defined transformation before calling the child draw method.

    true
    
    // enable "automatic" transformation when the object is activated
    onActivateEvent: function () {
    // reset the transformation matrix
    this.currentTransform.identity();
    // ensure the anchor point is the renderable center
    this.anchorPoint.set(0.5, 0.5);
    // enable auto transform
    this.autoTransform = true;
    ....
    }
    backgroundColor: Color

    define a background color for this container

    (0, 0, 0, 0.0)
    
    // add a red background color to this container
    this.backgroundColor.setColor(255, 0, 0);
    blendMode: string

    the blend mode to be applied to this renderable (see renderer setBlendMode for available blend mode)

    "normal"
    
    • CanvasRenderer#setBlendMode
    • WebGLRenderer#setBlendMode
    body: PhysicsBody

    the renderable physics body — the handle returned by the active PhysicsAdapter's addBody (or constructed imperatively via new Body(...)). Typed as the portable PhysicsBody interface; cast to the adapter-specific concrete type (MatterAdapter.Body, BuiltinAdapter.Body, or the legacy Body class) to reach native fields.

    // define a new Player Class
    class PlayerEntity extends me.Sprite {
    // constructor
    constructor(x, y, settings) {
    // call the parent constructor
    super(x, y , settings);

    // define a basic walking animation
    this.addAnimation("walk", [...]);
    // define a standing animation (using the first frame)
    this.addAnimation("stand", [...]);
    // set the standing animation as default
    this.setCurrentAnimation("stand");

    // add a physic body
    this.body = new me.Body(this);
    // add a default collision shape
    this.body.addShape(new me.Rect(0, 0, this.width, this.height));
    // configure max speed, friction, and initial force to be applied
    this.body.setMaxVelocity(3, 15);
    this.body.setFriction(0.4, 0);
    this.body.force.set(3, 0);
    this.isKinematic = false;

    // set the display to follow our position on both axis
    app.viewport.follow(this.pos, app.viewport.AXIS.BOTH);
    }

    ...

    }
    bodyDef: object | undefined

    Declarative body definition consumed by the active PhysicsAdapter when this renderable is added to a container. Adapter API only — leave undefined if you build a body imperatively via this.body = new Body(...).

    When set, the parent container forwards it to world.adapter.addBody(this, this.bodyDef), which constructs the underlying physics body (matter, builtin SAT, …) and assigns the engine-portable wrapper to this.body. This is the engine-portable path: the same bodyDef produces an equivalent body under any adapter.

    Typical fields: type ("static"/"dynamic"/"kinematic"), shapes, collisionType, collisionMask, restitution, frictionAir, density, gravityScale, isSensor, maxVelocity, fixedRotation. See BodyDefinition.

    undefined
    
    broadphase: QuadTree

    the instance of the game world quadtree used for broadphase (used by the builtin physic and pointer event implementation)

    clipping: boolean

    Specify if the container draw operation should clip its children to its own bounds

    false
    
    currentTransform: Matrix3d

    the renderable transformation matrix (4x4). For standard 2D use, only the 2D components are used (rotate around Z, scale X/Y, translate X/Y). For 3D use (e.g. Mesh), the full 4x4 matrix supports rotation around any axis, 3D translation, and perspective projection. Use the rotate(), scale(), and translate() methods rather than modifying this directly.

    edges: Vector2d[]

    The edges here are the direction of the nth edge of the polygon, relative to the nth point. If you want to draw a given edge from the edge value, you must first translate to the position of the starting point.

    enableChildBoundsUpdate: boolean

    Specify if the container bounds should automatically take in account all child bounds when updated (this is expensive and disabled by default, only enable if necessary)

    false
    
    floating: boolean

    If true, this renderable will be rendered using screen coordinates, as opposed to world coordinates. Use this, for example, to define UI elements.

    false
    
    fps: number

    the rate at which the game world is updated, may be greater than or lower than the display fps

    60
    

    timer.maxfps

    gpuTilemap: boolean

    Enable the WebGL2 procedural shader path for orthogonal tile layers. When true (default), eligible layers render via a single quad per tileset + a fragment shader doing per-pixel GID lookup — bypassing the per-tile drawImage loop entirely. Supported features on the shader path: animated tiles, all three flip bits (H/V/AD), per-layer opacity/tint/blend mode, and oversized bottom-aligned tiles up to 4 cells of overflow. Layers that don't qualify (Canvas/WebGL1, non-orthogonal, collection-of-image tilesets, non-zero tileoffset, or tile overflow beyond the shader's 4-cell limit) fall back to the legacy path automatically. Set to false to disable globally.

    true
    
    GUID: string

    (G)ame (U)nique (Id)entifier"
    a GUID will be allocated for any renderable object added
    to an object container (including the app.world container)

    indices: number[]

    a list of indices for all vertices composing this polygon

    isDirty: boolean

    when true the renderable will be redrawn during the next update cycle

    true
    
    isKinematic: boolean

    If true then physic collision and input events will not impact this renderable

    true
    
    isPersistent: boolean

    make the renderable object persistent over level changes

    false
    

    A mask limits rendering elements to the shape and position of the given mask object. So, if the renderable is larger than the mask, only the intersecting part of the renderable will be visible.

    undefined
    
    // apply a mask in the shape of a Star
    myNPCSprite.mask = new me.Polygon(myNPCSprite.width / 2, 0, [
    // draw a star
    {x: 0, y: 0},
    {x: 14, y: 30},
    {x: 47, y: 35},
    {x: 23, y: 57},
    {x: 44, y: 90},
    {x: 0, y: 62},
    {x: -44, y: 90},
    {x: -23, y: 57},
    {x: -47, y: 35},
    {x: -14, y: 30}
    ]);
    name: string

    The name of the renderable

    ""
    
    onChildChange: () => void

    a callback to be extended, triggered after a child has been added or removed

    onVisibilityChange: Function

    an event handler that is called when the renderable leave or enter a camera viewport

    undefined
    
    this.onVisibilityChange = function(inViewport) {
    if (inViewport === true) {
    console.log("object has entered the in a camera viewport!");
    }
    };
    physic: string

    Identifier of the active physics adapter, taken from the adapter's physicLabel field at Application construction — "builtin" (default — BuiltinAdapter), "matter" (@melonjs/matter-adapter), or a third-party label. The reserved value "none" is set when physics is disabled via physic: "none" in ApplicationSettings; World.step skips the simulation entirely under that label, and the rest of the world container behaves like a pure scene graph.

    User code can branch on the value without importing the adapter class:

    if (app.world.physic === "matter") {
    // matter-only setup (constraints, native queries, …)
    }
    • ApplicationSettings.physic
    • PhysicsAdapter.physicLabel
    "builtin"
    
    // disable physics entirely
    app.world.physic = "none";
    points: Vector2d[]

    Array of points defining the Polygon
    Note: If you manually change points, you must call recalcafterwards so that the changes get applied correctly.

    origin point of the Polygon

    postEffects: any[]

    the list of post-processing shader effects applied to this renderable (WebGL only). Effects are applied in order. Use addPostEffect, getPostEffect, and removePostEffect to manage effects, or assign directly. In Canvas mode, this property is ignored.

    []
    
    // add effects via helper methods
    mySprite.addPostEffect(new DesaturateEffect(renderer));
    mySprite.addPostEffect(new VignetteEffect(renderer));
    // assign directly
    mySprite.postEffects = [new SepiaEffect(renderer), new VignetteEffect(renderer)];
    preRender: boolean

    Enabled pre-rendering for all tile layers.
    If false layers are rendered dynamically, if true layers are first fully rendered into an offscreen canvas.
    the "best" rendering method depends of your game (amount of layer, layer size, amount of tiles per layer, etc.)
    Note : rendering method is also configurable per layer by adding a boolean "preRender" property to your layer in Tiled (https://doc.mapeditor.org/en/stable/manual/custom-properties/#adding-properties).

    false
    
    root: boolean

    whether the container is the root of the scene

    false
    
    type: string = "Rectangle"

    The shape type (used internally).

    updateWhenPaused: boolean

    Whether to update this object when the game is paused.

    false
    
    visibleInAllCameras: boolean

    If true, this floating renderable will be rendered by all cameras (e.g. background image layers). If false (default), floating elements are only rendered by the default camera (e.g. UI/HUD elements). Only applies to floating renderables in multi-camera setups.

    false
    

    Accessors

    • get bodies(): Set<Body>

      Active physics bodies in this simulation. Backed by the active adapter; mutating this set directly is no longer the recommended pattern — use world.adapter.addBody(...) / removeBody(...).

      Adapters that don't expose a native bodies Set (e.g. third-party integrations that own their own body storage) cause this getter to return a frozen empty Set, so any world.bodies.add(...) attempt throws TypeError instead of silently mutating a throwaway.

      Returns Set<Body>

    Methods

    • Add a physic body to the game world. Legacy API for code that constructed new Body(...) directly and now wants to register it with the active physics adapter.

      Parameters

      Returns World

      this game world

      Container.addChild

    • Returns true if the polygon contains the given point.
      (Note: it is highly recommended to first do a hit test on the corresponding
      bounding rect, as the function can be highly consuming with complex shapes)

      Parameters

      • x: number

        x coordinate or a vector point to check

      • y: number

        y coordinate

      Returns boolean

      True if the polygon contain the point, otherwise false

      if (polygon.contains(10, 10)) {
      // do something
      }
      // or
      if (polygon.contains(myVector2d)) {
      // do something
      }
    • Returns true if the polygon contains the given point.
      (Note: it is highly recommended to first do a hit test on the corresponding
      bounding rect, as the function can be highly consuming with complex shapes)

      Parameters

      Returns boolean

      True if the polygon contain the point, otherwise false

      if (polygon.contains(10, 10)) {
      // do something
      }
      // or
      if (polygon.contains(myVector2d)) {
      // do something
      }
    • The forEach() method executes a provided function once per child element.
      the callback function is invoked with three arguments:

      • The current element being processed in the array
      • The index of element in the array.
      • The array forEach() was called upon.

      Parameters

      • callback: Function

        function to execute on each element

      • OptionalthisArg: object

        value to use as this(i.e reference Object) when executing callback.

      Returns void

      // iterate through all children of this container
      container.forEach((child) => {
      // do something with the child
      child.doSomething();
      });
      container.forEach((child, index) => { ... });
      container.forEach((child, index, array) => { ... });
      container.forEach((child, index, array) => { ... }, thisArg);
    • returns the list of children with the specified name
      as defined in Tiled (Name field of the Object Properties)
      note : avoid calling this function every frame since it parses the whole object list each time

      Parameters

      • name: string | number | boolean | RegExp

        child name

      Returns Renderable[]

      Array of children

    • return the child corresponding to the given property and value.
      note : avoid calling this function every frame since it parses the whole object tree each time

      Parameters

      • prop: string

        Property name

      • value: string | number | boolean | RegExp

        Value of the property

      • objList: any[] = []

      Returns Renderable[]

      Array of children

      // get the first child object called "mainPlayer" in a specific container :
      let ent = myContainer.getChildByProp("name", "mainPlayer");

      // or query the whole world :
      let ent = container.getChildByProp("name", "mainPlayer");

      // partial property matches are also allowed by using a RegExp.
      // the following matches "redCOIN", "bluecoin", "bagOfCoins", etc :
      let allCoins = container.getChildByProp("name", /coin/i);

      // searching for numbers or other data types :
      let zIndex10 = container.getChildByProp("z", 10);
      let inViewport = container.getChildByProp("inViewport", true);
    • Get post-processing shader effects. When called with a class, returns the first effect matching the given class. When called without arguments, returns the full effects array.

      Parameters

      • OptionaleffectClass: Function

        the effect class to search for

      Returns any

      the matching effect, the effects array, or undefined

      const desat = sprite.getPostEffect(DesaturateEffect);
      const allEffects = sprite.getPostEffect();
    • Returns true if the vertices composing this polygon form a convex shape (vertices must be in clockwise order).

      Returns boolean | null

      true if the vertices are convex, false if not, null if not computable

    • Legacy collision callback — fires every frame this renderable body is overlapping another body. Kept for backward compatibility with code written against pre-19.5 melonJS; semantics are unchanged from the 19.4 contract.

      NOTE — onCollision is NOT equivalent to Renderable.onCollisionActive. The two handlers exist side by side and have intentionally different contracts:

      onCollision (legacy) onCollisionActive (modern)
      Cadence for dynamic-dynamic pairs 2× per frame per side 1× per frame per side
      response.a semantics Fixed per pair (first body in detector call) Always the receiver (response.a === this)
      response.b semantics Fixed per pair Always the partner (response.b === other)
      response.normal / response.depth ✓ — normal.y < -0.7 = "push me up"
      return false to skip push-out ✓ (honored by SAT) ✗ — use bodyDef.isSensor or setSensor instead

      If you're writing new code, prefer onCollisionActive. Keep onCollision only when its every-frame, return-false, fixed-a/b semantics are what you want.

      Parameters

      • _response: any
      • _other: any

      Returns boolean

      true if the object should respond to the collision (its position and velocity will be corrected); the return value is only honored by the builtin SAT adapter.

      // legacy collision handler — note the receiver-side check on response.a
      onCollision(response) {
      if (response.b.body.collisionType === me.collision.types.ENEMY_OBJECT) {
      this.pos.sub(response.overlapV);
      this.hurt();
      return false; // skip the SAT push-out
      }
      return true;
      }
    • OnDestroy Notification function
      Called by engine before deleting the object. Stage.destroy(app) forwards the active Application, so subclasses that wire teardown against the app object can override as onDestroyEvent(app).

      Parameters

      • ..._args: any[]

        forwarded by destroy(...args); Stage passes the Application instance

      Returns void

    • Rotate this renderable by the specified angle (in radians). When called with just an angle, rotates around the Z axis (2D rotation). When called with an angle and a Vector3d axis, rotates around that axis in 3D.

      Parameters

      • angle: number

        The angle to rotate (in radians)

      • Optionalv: any

        the axis to rotate around (defaults to Z axis for 2D)

      Returns Renderable

      Reference to this object for method chaining

    • scale the renderable around his anchor point. Scaling actually applies changes to the currentTransform member which is used by the renderer to scale the object when rendering. It does not scale the object itself. For example if the renderable is an image, the image.width and image.height properties are unaltered but the currentTransform member will be changed.

      Parameters

      • x: number

        a number representing the abscissa of the scaling vector.

      • Optionaly: number = x

        a number representing the ordinate of the scaling vector.

      • Optionalz: number = 1

        a number representing the depth of the scaling vector.

      Returns Renderable

      Reference to this object for method chaining

    • Automatically set the specified property of all childs to the given value

      Parameters

      • prop: string

        property name

      • value: object

        property value

      • Optionalrecursive: boolean

        recursively apply the value to child containers if true

      Returns void

    • set new value to the Polygon

      Parameters

      • x: number

        position of the Polygon

      • y: number

        position of the Polygon

      • points: PolygonVertices | LineVertices

        array of vector or vertices defining the Polygon

      Returns World

      this instance for object chaining

    • Shifts the Polygon to the given position vector.

      Parameters

      • x: number

        The x coordinate or a vector point to shift to.

      • Optionaly: number

        The y coordinate. This parameter is required if the first parameter is a number.

      Returns void

      polygon.shift(10, 10);
      // or
      polygon.shift(myVector2d);
    • Shifts the Polygon to the given position vector.

      Parameters

      Returns void

      polygon.shift(10, 10);
      // or
      polygon.shift(myVector2d);
    • update the physics simulation by one step (called by the game world update method)

      Parameters

      • dt: number

        the time passed since the last frame update

      Returns void