melonJS
    Preparing search index...

    Class TileLayer

    A layer of tiles on a grid: one tile a cell, each a tile of one of the layer's tilesets, optionally flipped. It is what a tile map is made of, whatever editor the map comes from: a Tiled layer is one (TMXLayer), and so is a layer a loader for another format builds from its own data.

    It draws itself (on the GPU where it can, see TileLayer#renderMode), is in view as far as its tiles reach, and is read and changed a cell at a time: TileLayer#cellAt, TileLayer#getTile, TileLayer#setTile, TileLayer#setCell, TileLayer#clearTile, and for what a tile says of itself TileLayer#getTileProperties and TileLayer#setTileProperties.

    // a 20 x 15 layer of 16 px cells, drawn from one tileset
    const tileset = new Tileset({ name: "ground", image: "ground", tilewidth: 16, tileheight: 16 });
    const layer = new TileLayer({
    name: "floor",
    cols: 20,
    rows: 15,
    tilewidth: 16,
    tileheight: 16,
    tilesets: new TilesetGroup([tileset]),
    });
    // the tileset's fourth tile in the top left cell
    layer.setCell(0, 0, tileset.firstgid + 3);
    app.world.addChild(layer, 1);

    Hierarchy (View Summary)

    Index
    • Parameters

      • def: {
            blendMode?: string;
            class?: string;
            cols: number;
            name?: string;
            offsetx?: number;
            offsety?: number;
            opacity?: number;
            orientation?: string;
            parallaxAnchor?: { x: number; y: number };
            parallaxOrigin?: { x: number; y: number };
            parallaxScale?: number;
            ratio?: number | { x: number; y: number };
            renderer?: TileMapRenderer;
            renderMode?: string;
            renderorder?: string;
            rows: number;
            startx?: number;
            starty?: number;
            tileheight: number;
            tilesets: TilesetGroup;
            tilewidth: number;
            tint?: any;
            z?: number;
        }

        what the layer is

        • OptionalblendMode?: string

          its blend mode

        • Optionalclass?: string

          a class name of the game's own

        • cols: number

          the number of columns

        • Optionalname?: string

          the layer's name

        • Optionaloffsetx?: number

          how far it is moved across, in pixels

        • Optionaloffsety?: number

          how far it is moved down, in pixels

        • Optionalopacity?: number

          its opacity (0 hides it)

        • Optionalorientation?: string

          the kind of grid; any other than "orthogonal" needs renderer

        • OptionalparallaxAnchor?: { x: number; y: number }
        • OptionalparallaxOrigin?: { x: number; y: number }
        • OptionalparallaxScale?: number
        • Optionalratio?: number | { x: number; y: number }

          its scrolling ratio, see TileLayer#ratio

        • Optionalrenderer?: TileMapRenderer

          the renderer of the map it belongs to; by default one for its own grid

        • OptionalrenderMode?: string

          how it is drawn, see TileLayer#renderMode

        • Optionalrenderorder?: string

          the order its tiles are drawn in

        • rows: number

          the number of rows

        • Optionalstartx?: number

          the column, in its map's tile coordinates, of its first column

        • Optionalstarty?: number

          the row, in its map's tile coordinates, of its first row

        • tileheight: number

          the height of a cell, in pixels

        • tilesets: TilesetGroup

          the tilesets its tiles come from

        • tilewidth: number

          the width of a cell, in pixels

        • Optionaltint?: any

          a tint for its tiles, as a color or a CSS color string

        • Optionalz?: number

          its draw order

      Returns TileLayer

    alpha: number

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

    Opacity cascades: it is multiplied with the alpha already on the renderer, so fading a Container fades everything inside it, and a child at alpha 0.5 inside a parent at 0.5 draws at 0.25. Each renderable keeps its own value — the composition happens at draw time, and is undone when the renderable is done.

    That is different from Container#setChildsProperty, which assigns a value onto the children themselves. Use alpha to fade a subtree, and setChildsProperty to change what the children are.

    • Renderable#setOpacity
    • Renderable#getOpacity
    • Container#setChildsProperty
    1.0
    
    // fades the whole rig, parts included
    myModel.alpha = 0.3;
    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}, or (since 19.9) a plain string preset such as bottom.
    At construction time, settings.anchorPoint also accepts the named presets "center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right" on every renderable that consumes it (Sprite, Entity, Collectable, ImageLayer, Text, BitmapText, Sprite3d and subclasses).
    Note: a body's collision shapes are measured from the same frame this places the renderable in, so a shape of Rect(0, 0, width, height) covers the renderable whatever the anchor is (since 20.7; before that shapes were measured from pos regardless, and a non-corner anchor collided where it was not drawn). A shape's own pos still offsets it inside that frame. A renderable that has cleared Renderable#applyAnchorTransform takes no offset at all, on the drawing or on its shapes. Note also that the adapters read the anchor when the body is created, so changing it afterwards moves the drawing but not an already-built body.

    <0.5,0.5>
    
    animatedTilesets: Tileset[]

    All animated tilesets in this layer

    applyAnchorTransform: boolean

    Whether Renderable#preDraw applies the Renderable#anchorPoint offset to the renderer transform.

    When true (the default), the renderable is shifted by -anchorPoint × (width, height) so its anchor — not its top-left corner — aligns with its position. Correct for sprites and other 2D renderables.

    Set to false for a renderable that emits its own final world coordinates and takes its origin from geometry rather than a bounds box — e.g. a Mesh on the Camera3d world-space path (a 3D mesh is positioned by its transform and has no anchor). The WebGL mesh batcher reuses this same renderer transform as its view matrix, so applying the normalized anchor there would shift every mesh by half its OWN bounds box; because scene meshes size that box per node, props and the platforms they rest on would drift apart and overlap.

    true
    

    Mesh#preDraw

    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;
    ....
    }
    blendMode: string

    the blend mode to be applied to this renderable — any of the modes listed on CanvasRenderer#setBlendMode, honoured identically by every renderer

    "normal"
    
    • CanvasRenderer#setBlendMode
    • WebGLRenderer#setBlendMode

    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, 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 BodyDefinitionInit.

    shapes is normally a list of collision shapes, but it can also name a collision shape file preloaded as JSON, paired with id naming the body to read out of it. The file is resolved before any adapter sees the definition, so the same one works unchanged on every backend.

    undefined
    
    // a shape authored in code
    this.bodyDef = {
    type: "dynamic",
    shapes: [new me.Rect(0, 0, this.width, this.height)],
    };
    // shapes drawn in a physics-shape editor, preloaded as JSON with
    // { name: "shapes", type: "json", src: "data/physics/shapes.json" }
    this.bodyDef = { type: "dynamic", shapes: "shapes", id: "hotdog" };

    // the density, friction and bounce the shapes were authored with
    // come with them, unless the definition states otherwise (each is
    // honoured by whichever backends support it):
    this.bodyDef = {
    type: "dynamic",
    shapes: "shapes",
    id: "hotdog",
    restitution: 0.9, // wins over whatever the file carries
    };
    canvasRenderer: CanvasRenderer | undefined
    class: string

    the layer class

    collisionMask?: number
    collisionType?: number

    Optional per-shape collision settings, honoured by Body#addShape and defaulted there. Declared rather than initialized: the body writes them when the shape joins it, so a class field here would emit an undefined own property on every shape ever built. See addShape for the table of defaults and what each one does.

    Body#addShape

    cols: number

    the number of columns in the layer

    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.

    dataVersion: number

    Monotonically-increasing counter bumped by setTile and clearTile. Renderers can compare against a stashed value to detect mutations and decide whether to re-upload the layer data to the GPU.

    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.

    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
    
    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)

    height: number
    indices: number[]

    a list of indices for all vertices composing this polygon, filled in by Polygon#getIndices and invalidated by Polygon#recalc.

    A subclass may repurpose this name for geometry of its own: a Mesh holds a GPU index buffer here, a typed array rather than a plain one. recalc therefore only clears the slot when it owns it — anything else reading it should check what it got.

    isActive?: boolean

    false takes this shape out of collision without removing it

    isAnimated: boolean

    Layer contains tileset animations

    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: set it false for it to collide with physics bodies, or to receive the pointer events registered on it with input.registerPointerEvent. An opt-in, left out by default.

    It does not decide what Camera3d#pick returns: picking a mesh needs neither a body nor an event, so it ignores this flag. A mesh is left out of pick() with Mesh#pickable instead, an opt-out that touches neither collisions nor events.

    true
    

    Mesh#pickable

    // a button: it must receive its pointer events
    button.isKinematic = false;
    input.registerPointerEvent("pointerdown", button, onPress);

    // a floor under a Camera3d: it collides, but is not what a click picks
    floor.isKinematic = false; // collisions (and events)
    floor.pickable = false; // camera.pick() looks past it

    // a crate picked with camera.pick(): no body, no events, nothing to set
    const hit = camera.pick(pointer.gameScreenX, pointer.gameScreenY, app.world);
    isPersistent: boolean

    make the renderable object persistent over level changes

    false
    
    isTrigger?: boolean

    true reports contacts but skips the position correction

    layerData: Uint16Array<ArrayBufferLike>

    The raw tile data for this layer. Each cell occupies two consecutive Uint16 slots: the GID (with flip bits stripped) and a 3-bit flip mask. Cell (x, y) is at layerData[(y * cols + x) * 2] (row-major), counted from the layer's first cell: the map's tile (x + startx, y + starty).

    The 16-bit GID slot caps per-tileset GIDs at 65 535. This matches the planned WebGL2 shader path (RG16UI index texture) — switching to Uint32Array would force a truncating copy at GPU upload time.

    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}
    ]);
    maxTileSize: { height: number; width: number }
    name: string

    The name of the renderable

    ""
    
    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!");
    }
    };
    orientation: string
    parallaxAnchor: Vector2d

    The point of the camera's view that is on TileLayer#parallaxOrigin when the layer is where it was placed: (0, 0) for the view's top left corner (the camera's position), (0.5, 0.5) for its centre, (1, 1) for its bottom right corner.

    <0,0>
    
    parallaxOrigin: Vector2d

    Where the camera is when the layer is where it was placed, in the coordinates the layer's pos is in: at the world's origin by default, as for an ImageLayer. The point of the camera's view that is measured is TileLayer#parallaxAnchor.

    <0,0>
    
    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

    postEffectNeedsCapture: boolean

    whether a single post effect on this renderable needs an offscreen capture instead of the renderer's shader-swap fast path.

    One effect is normally applied by drawing the renderable with the effect's own program rather than capturing and post-processing it, which costs no render target. That is only equivalent when everything the renderable draws is a textured quad. fillRect and the shape dispatch go through a batcher that never looks at that shader, so a single effect on a renderable that draws with primitives silently does nothing. Set this and the capture is used instead, at the cost of a render target while the effect is active.

    Two or more effects always capture, so this only ever changes the single-effect case.

    false
    
    class Bar extends Renderable {
    constructor(x, y, w, h) {
    super(x, y, w, h);
    // this draws itself with primitives, not as a sprite
    this.postEffectNeedsCapture = true;
    }
    draw(renderer) {
    renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
    }
    }
    postEffects: (ShaderEffect | GLShader)[]

    the list of post-processing shader effects applied to this renderable (GPU backends — WebGL and WebGPU). Effects are applied in order. Use addPostEffect, getPostEffect, and removePostEffect to manage effects, or assign directly. On the Canvas renderer effects stay inert (the scene keeps rendering un-effected).

    []
    
    // 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 | undefined
    ratio: Vector2d

    The layer's scrolling ratio, as an ImageLayer's: how fast the layer scrolls across the screen, as a share of the world's pace. At (1, 1) it scrolls with the world, as any layer does; at (0, 0) it stays where it is on the screen; at (0.5, 0.5) it scrolls at half the pace, as a backdrop further away; above 1, faster, as a foreground. A Tiled layer's parallax factor is read into it, and so is a ratio custom property of the layer.

    Set both parts (ratio.set(0.5, 0.5)): a part that is not a number scrolls with the world.

    It changes where the layer is drawn, for each camera, and nothing else: getTile, cellAt and the layer's bounds are those of the layer where it was placed.

    <1.0,1.0>
    
    // far hills, at half the level's pace
    hills.ratio.set(0.5, 0.5);
    renderer: TileMapRenderer | undefined
    renderMode: string

    How this layer is rendered. Resolved by onActivateEvent to one of:

    • "shader" — GPU procedural shader path, on WebGL 2 and WebGPU, for orthogonal, isometric, staggered and hexagonal maps (single quad per tileset, fragment GID lookup)
    • "prerender"— offscreen-canvas bake at activation, blitted as one drawImage per frame
    • "perTile" — per-frame loop, one drawImage per visible tile

    User code may set this to one of the above values (or the special "auto") before the layer is activated to override the engine's default choice; on a Tiled layer, a custom property named renderMode does. If a forced mode is ineligible (e.g. "shader" on Canvas), a one-shot warning is emitted at activation and the layer falls back to the legacy path.

    "auto"
    
    renderorder: string

    the order in which tiles on orthogonal tile layers are rendered. (valid values are "left-down", "left-up", "right-down", "right-up").

    "right-down"
    
    rows: number

    the number of rows in the layer

    startx: number

    the column, in the map's tile coordinates, of the layer's first column. 0, except on an infinite map whose layer holds tiles left of the map's origin: there it is negative, and the layer's columns are startx to startx + cols - 1, the column numbers Tiled shows

    0
    
    starty: number

    the row, in the map's tile coordinates, of the layer's first row. 0, except on an infinite map whose layer holds tiles above the map's origin: there it is negative, and the layer's rows are starty to starty + rows - 1, the row numbers Tiled shows

    0
    
    tileheight: number
    tileset: Tileset | null
    tilesets: TilesetGroup

    The Layer corresponding Tilesets

    tilewidth: number
    type: string = "Rectangle"

    The shape type (used internally).

    updateWhenPaused: boolean

    Whether to update this object when the game is paused.

    On a container it covers everything under it: a child steps through a pause on its own opt-in or on one from any container above it, so a pause menu flags itself once and its nested labels follow.

    false
    
    visibilityLayer: number

    The layers this renderable belongs to, as bits (1, 2, 4, 8... up to 32 of them). A camera draws it only if it shares a bit with the camera's Camera2d#cullMask: by default every renderable is on layer 1 and every camera draws every layer, so it shows in all of them. Put something on a layer a camera leaves out to keep it off that camera only, such as the particles off a minimap. A container left out is left out with everything inside it (the world included), and a renderable on no layer, 0, is drawn by no camera.

    It decides what a camera draws, and nothing else: the renderable still updates, collides and receives pointer events. A Light2d a camera leaves out, itself or a container it is in, neither glows, nor cuts its hole in the darkness, nor lights normal-mapped sprites in that camera (a Light3d lights the meshes of every camera). A floating renderable must also pass the camera's floating rule (see Renderable#visibleInAllCameras). On an object of a Tiled map it can be set as an int custom property of the object.

    1
    

    Camera2d#cullMask

    // particles on their own layer, and a minimap that leaves it out
    const PARTICLES = 2;
    emitter.visibilityLayer = PARTICLES;
    minimap.cullMask = ~PARTICLES;
    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), zoomed or not. Only applies to floating renderables in multi-camera setups.

    false
    
    width: number
    x: number

    Horizontal layer offset in tiles

    0
    
    y: number

    Vertical layer offset in tiles

    0
    
    • get isFloating(): boolean

      Whether the renderable object is floating (i.e. used screen coordinates), or contained in a floating parent container

      Returns boolean

      Renderable#floating

    • get sortOffset(): number

      An offset, in pixels, added to this renderable's position when its parent container sorts its children on "y" (or "x"), and used for nothing else. It never moves the renderable and never changes where or how it is drawn: it only decides whether it is drawn before or after its siblings, and so which one is on top, and which one a pointer hits.

      A container sorted on "y" draws its children from the smallest pos.y to the largest, the last one on top. A child with a sortOffset is lined up as if it stood that many pixels lower (positive) or higher (negative), while staying where it is. Use it when pos is not the point a renderable should be sorted by: the top of a Tiled tile object's image, the top left corner of a container, or the top of a particle emitter's spawn area.

      • A container that keeps itself sorted (autoSort, the default) picks a change up at its next update; with autoSort off, call its sort().
      • Containers sorted on "z" or "depth" ignore it, and on "x" and "y" a different pos.z still decides first.
      • Two children that come out equal keep their order, which draws the one added last BEHIND the other: an offset of 1 settles such a tie on purpose.
      • A renderable taken from a pool starts again at 0.

      Returns number

      0
      

      if set to anything but a finite number

      // a torch hung on a wall at the wall's own position: line it up
      // 1 px lower, so that it is drawn over the wall
      torch.sortOffset = 1;
      // a particle emitter's pos is the top of its spawn area. Dust rising at
      // the foot of a door sits far below the door's pos, and would be drawn
      // over everything between the two: line it up with the door instead
      dust.sortOffset = door.pos.y - dust.pos.y;
    • set sortOffset(value: number): void

      Parameters

      • value: number

      Returns void

    • get tint(): Color

      define a tint for this renderable. a (255, 255, 255) r, g, b value will remove the tint effect.

      Returns Color

      (255, 255, 255)
      
      // add a red tint to this renderable
      this.tint.setColor(255, 128, 128);
      // remove the tint
      this.tint.setColor(255, 255, 255);
    • set tint(value: string | Color): void

      Takes a Color to copy, or a CSS colour string.

      It COPIES rather than holds, so a caller that goes on mutating what it passed does not steer this renderable's tint by accident. What the getter hands back is always a Color, whichever form went in.

      Parameters

      • value: string | Color

        the colour to tint with

      Returns void

    • Return the Tile object at the specified tile coordinates

      Parameters

      • x: number

        column, in the map's tile coordinates (as Tiled shows them: on an infinite map, from TileLayer#startx); a fraction is rounded down

      • y: number

        row, in the map's tile coordinates (on an infinite map, from TileLayer#starty); a fraction is rounded down

      • OptionalboundsCheck: number

        check first if within the layer bounds

      Returns Tile

      corresponding tile or null if there is no defined tile at the position or if outside of the layer bounds

      // return the first tile at offset 0, 0
      let tile = layer.cellAt(0, 0);
    • clear the tile at the specified position (no change outside the layer)

      Parameters

      • x: number

        column, in the map's tile coordinates (on an infinite map, from TileLayer#startx)

      • y: number

        row, in the map's tile coordinates (on an infinite map, from TileLayer#starty)

      Returns void

      app.world.getChildByType(me.TMXLayer).forEach(function(layer) {
      // clear all tiles at the given x,y coordinates
      layer.clearTile(x, y);
      });
    • 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

      • vector: XYPoint

      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
      }
    • Where this renderable IS in the game world — its own pos plus every ancestor's, as a Vector3d so the z component is summed across the chain too (important for Camera3d's frustum culling, which previously read obj.depth — local pos.z — and mis-culled children nested under a container with its own non-zero depth).

      Reach for this for anything positional: culling, distance checks, hit tests, placing one renderable relative to another. It is cheap, and it is what the engine's own culling uses.

      Reach for Renderable#getWorldTransform instead when a position is not enough — when rotation, scale or flip along the ancestor chain matters, or when you need to map an arbitrary point rather than just the origin. This method sums translations only, so under a rotated or scaled ancestor it reports where the renderable's pivot is and nothing about how its content is oriented.

      Note the two also frame the question differently. This one is "where am I"; getWorldTransform() is "what space is my content drawn in". For a Container those coincide, because a container offsets its children by its own position. For a leaf they differ by exactly that position, which a leaf applies inside its own draw().

      The returned vector is pooled and reused — copy it if you need to hold onto the value across another call.

      Returns Vector3d

      this renderable's absolute position

      Renderable#getWorldTransform

    • Protected

      The transform this renderable interposes between its ancestor's frame and the frame its own content is drawn in — a mirror of what Renderable#preDraw applies to the renderer, as a matrix.

      This is not Renderable#currentTransform. A renderable's placement is split across two members: pos holds where it is, and currentTransform holds only what rotate() / scale() / translate() accumulate — it never contains the position. preDraw composes the two by conjugation, so a rotation pivots about the renderable's position rather than the origin. On a renderable you never rotated, currentTransform is therefore the identity and says nothing about where its content lands, while this method returns the translation that actually places it.

      Container extends this with the offset it applies to its children, which a leaf renderable does not have: a leaf's own draw() places itself from pos.

      Parameters

      • out: Matrix3d

        matrix to write into; nothing is stored on the renderable itself, so callers own the lifetime

      Returns Matrix3d

      out, for chaining

      Renderable#getWorldTransform

    • 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[] | ShaderEffect | GLShader | undefined

      the matching effect, the effects array, or undefined

      const desat = sprite.getPostEffect(DesaturateEffect);
      const allEffects = sprite.getPostEffect();
    • Return the Tile object at the specified position

      Parameters

      • x: number

        X coordinate (in world/pixels coordinates)

      • y: number

        Y coordinate (in world/pixels coordinates)

      Returns Tile

      corresponding tile or null if there is no defined tile at the coordinate or if outside of the layer bounds: the tile drawn there, whose col and row are the cell TileLayer#cellAt reads

      // get the TMX Map Layer called "Front layer"
      let layer = app.world.getChildByName("Front Layer")[0];
      // get the tile object corresponding to the latest pointer position
      let tile = layer.getTile(me.input.pointer.x, me.input.pointer.y);
    • return a new Tile object for the given tile id, to place with TileLayer#setTile

      Parameters

      • tileId: number

        global tile id: the tileset's firstgid plus the tile's id in the tileset

      • x: number

        column of the tile (in the map's tile coordinates), stored as its col

      • y: number

        row of the tile (in the map's tile coordinates), stored as its row

      Returns Tile

      the tile object

      // turn the cell at column 3, row 5 into the tileset's tile 7
      const tileset = layer.tilesets.getTilesetByIndex(0);
      layer.setTile(layer.getTileById(tileset.firstgid + 7, 3, 5), 3, 5);
    • Return the TileId of the Tile at the specified position

      Parameters

      • x: number

        X coordinate (in world/pixels coordinates)

      • y: number

        Y coordinate (in world/pixels coordinates)

      Returns number

      TileId or null if there is no Tile at the given position

    • The properties of the tile in a cell: those of its tile in the tileset (Tileset#getTileProperties), with those the cell has of its own over them (TileLayer#setTileProperties). One call whatever the map was made with: a Tiled tile's custom properties, an LDtk tile's custom data and tags, a Sprite Fusion tile's attributes. (An LDtk layer that stacks tiles or places them off its grid is a PlacedTileLayer, which has no cells to ask.)

      Read it, do not write to it: the object may be the one the tileset keeps for every tile of that id.

      Parameters

      • x: number

        column, in the map's tile coordinates

      • y: number

        row, in the map's tile coordinates

      Returns object | undefined

      the properties, or undefined when the cell is empty, outside the layer, or its tile has none

      // what the player stands on
      const tile = layer.getTile(player.centerX, player.getBounds().bottom + 1);
      if (tile !== null && layer.getTileProperties(tile.col, tile.row)?.type === "lava") {
      player.hurt();
      }
    • The space this renderable's content is drawn IN, as a matrix — the full form of Renderable#getAbsolutePosition, which sums positions up the ancestor chain and therefore cannot represent the rotation, scale or flip accumulated along the way.

      Reach for getAbsolutePosition() instead for ordinary positional work — culling, distance checks, hit tests. It is cheaper and it is what the engine culls with. Use this when a position is not enough:

      • an ancestor is rotated or scaled, so a translation cannot describe the result
      • you need to map an arbitrary point, not just the origin — a corner, a click position, one renderable's coordinates into another's space
      • you need to compose or invert the transform (inv(A) · B converts between two frames, which is how ParticleEmitter.referenceSpace measures particles against a container that is not their parent)

      The two also frame the question differently, and it shows on a leaf. getAbsolutePosition() is "where am I"; this is "what space is my content drawn in". For a Container those coincide, because a container offsets its children by its own position. For a leaf they differ by exactly that position, which a leaf applies inside its own draw(). So with no rotation, scale or flip anywhere, a container's translation column equals its getAbsolutePosition() while a leaf's equals its PARENT's.

      The walk stops at a floating ancestor, because a floating renderable draws in screen space: Container#draw resets the transform outright for those, so the chain genuinely ends there rather than continuing to the root.

      The camera needs no special handling — Camera2d folds its view transform into the root container's currentTransform, so it is picked up like any other level.

      Parameters

      • out: Matrix3d

        matrix to write into; nothing is stored on the renderable itself, so callers own the lifetime

      Returns Matrix3d

      out, for chaining

      Renderable#getAbsolutePosition

      // map a point from one renderable's space into another's
      const from = a.getWorldTransform(new Matrix3d());
      const into = b.getWorldTransform(new Matrix3d()).invert();
      const point = new Vector2d(10, 20); // in a's space
      from.apply(point); // -> world
      into.apply(point); // -> b's space
      // just need to know where something is? use the cheaper call
      const where = renderable.getAbsolutePosition();
    • 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: ResponseObject

        the SAT response object; the legacy handler receives this, not the adapter's CollisionResponse, which is why normal and depth are absent from the table above

      • other: Renderable

        the other renderable touching this one (a reference to response.a or response.b)

      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. Receives whatever destroy(...args) was called with — the production path (Container.removeChildNow) passes nothing. Stage has its own onDestroyEvent, which does forward the active Application.

      Parameters

      • ..._args: any[]

        forwarded by destroy(...args); normally empty

      Returns void

    • Prepare the rendering context before drawing (automatically called by melonJS). This will apply any defined transforms, anchor point, tint or blend mode and translate the context accordingly to this renderable position.

      Parameters

      Returns void

      • Renderable#draw
      • Renderable#postDraw
    • 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. When called with a Quaternion, rotates by the rotation it holds.

      Parameters

      • angle: number | Quaternion

        The angle to rotate (in radians), or a quaternion

      • Optionalv: Vector3d

        the axis to rotate around (defaults to Z axis for 2D); not used with a quaternion

      Returns TileLayer

      Reference to this object for method chaining

      // turn a mesh from facing +X to facing along `dir`
      mesh.rotate(new Quaternion().setFromUnitVectors(new Vector3d(1, 0, 0), dir));
    • 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 TileLayer

      Reference to this object for method chaining

    • Set a cell by tile id: what TileLayer#setTile does, without a Tile object to make first. The way to fill a layer built in code, and to change many cells at once (no change outside the layer).

      Parameters

      • x: number

        column, in the map's tile coordinates (see TileLayer#startx)

      • y: number

        row, in the map's tile coordinates (see TileLayer#starty)

      • gid: number

        global tile id: the tileset's firstgid plus the tile's id in the tileset; 0 clears the cell

      • OptionalflipMask: number = 0

        how the tile is flipped: 1 across, 2 down, 4 along its diagonal, added together

      Returns void

      // a checkerboard of the tileset's first two tiles
      for (let row = 0; row < layer.rows; row++) {
      for (let col = 0; col < layer.cols; col++) {
      layer.setCell(col, row, tileset.firstgid + ((col + row) & 1));
      }
      }
    • Move this renderable, optionally in three dimensions.

      pos holds an ObservableVector3d, but the geometry this class inherits from declares it as a 2D vector, so from TypeScript pos.set(x, y) takes two arguments and silently writes a zero z. Anything with a depth then drops to the near plane. Reaching past that previously meant a double cast or assigning pos.x, pos.y and depth by hand, which is why that pattern is written out dozens of times across the examples.

      Omitting z leaves the depth exactly as it was, rather than zeroing it. That is the whole difference from pos.set(x, y), and it is what makes this safe to call on a 2D sprite that happens to sit at a depth, or on a Camera2d, without having to know whether it does.

      Parameters

      • x: number

        the new x position

      • y: number

        the new y position

      • Optionalz: number

        the new depth; left untouched when omitted

      Returns TileLayer

      this renderable, for chaining

      sprite.setPosition(120, 64);        // 2D: depth unchanged
      mesh.setPosition(0, -20, 140); // 3D
      camera.setPosition(0, 0, -300).lookAt(player);
    • 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 TileLayer

      this instance for object chaining

    • Give the tile in a cell properties of its own, which TileLayer#getTileProperties returns over those of its tile in the tileset. They belong to the tile placed there: writing the cell (TileLayer#setTile, TileLayer#setCell, TileLayer#clearTile) drops them.

      Parameters

      • x: number

        column, in the map's tile coordinates

      • y: number

        row, in the map's tile coordinates

      • Optionalproperties: object

        the properties; leave out to remove the cell's own

      Returns void

      // this one door is locked, the other doors of the tileset are not
      layer.setTileProperties(12, 4, { locked: true });
    • Tint this renderable, chainably.

      Exactly Renderable#tint's own setter, returning the renderable so it can be chained with the other set* methods. It exists because tint is a live Color, so reaching for it means choosing between setColor (0 to 255), setFloat (0 to 1), parseCSS, setHSL and setLinear — and picking the wrong one is silent, it just renders the wrong colour.

      Deliberately sRGB only. A LINEAR value, which in practice means a glTF baseColorFactor or emissiveFactor, stays an explicit tint.setLinear(...) so the conversion is never silent; for a mesh built from an asset, pass Mesh#baseColorFactor as a setting and the loader's value is applied for you.

      Parameters

      • value: string | Color

        a Color to copy, or a CSS colour string

      Returns TileLayer

      this renderable, for chaining

      sprite.setTint("#ff8800");
      // the same on any renderable, mesh included
      mesh.setTint(theme.accent).setOpacity(0.5);
      // remove a tint
      sprite.setTint("#ffffff");
    • 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

      • vector: XYPoint

      Returns void

      polygon.shift(10, 10);
      // or
      polygon.shift(myVector2d);
    • Translate the renderable by the specified offset.

      Parameters

      • x: number | XYPoint | Vector2d | Vector3d

        x offset, or a vector (any {x, y} or {x, y, z} point) to translate by

      • Optionaly: number = 0

        y offset, ignored when the first argument is a vector

      • Optionalz: number = 0

        z offset, ignored when the first argument is a vector

      Returns TileLayer

      Reference to this object for method chaining