melonJS
    Preparing search index...

    Class Light2d

    A 2D point light.

    Light2d carries the properties of a light (color, radii, intensity, height, flags, position) and asks the active renderer to render it via renderer.drawLight(this). The renderer picks the right machinery:

    • WebGL: a single quad through a shared procedural radial-falloff fragment shader (RadialGradientEffect). One shader is reused across every Light2d on the renderer; no per-light texture is allocated.
    • Canvas: a small Gradient config object (cached per-light in a WeakMap and rebuilt only when radii / color / intensity change), rasterized via Gradient.toCanvas() on every draw into a single shared CanvasRenderTarget, then composited with drawImage. The per-light cache holds only the gradient stops, not the bitmap — the render target is one-per-engine.

    Light2d itself is renderer-agnostic — no shader knowledge, no canvas allocation, no renderer reference held.

    stage.lights

    Hierarchy (View Summary)

    Index

    Constructors

    • Create a 2D point light.

      A Light2d is a first-class world Renderable: add it to a container with app.world.addChild(light) (or any sub-container, including a Sprite, so the light follows the parent via its transform). On activation, the light auto-registers with the active Stage's lighting set so the ambient overlay (Stage.ambientLight) cuts a hole at the light's visible area, and a radial gradient from the given color (full intensity at center → fully transparent at the radius) is composited additively on top — producing a soft spot light. Rendering happens inside each Camera2d's post-effect FBO bracket so any camera shader (vignette, color-matrix, scanlines, etc.) wraps the lighting output.

      Set radiusY to a different value than radiusX for a stretched (elliptical) light. The intensity parameter scales the gradient's inner alpha; the Stage.ambientLight color and alpha control how dark the unlit areas are. Use light.blendMode to override the default additive blend if needed.

      Parameters

      • x: number

        The horizontal position of the light's center (matches Ellipse(x, y, w, h) conventions).

      • y: number

        The vertical position of the light's center.

      • radiusX: number

        The horizontal radius of the light.

      • OptionalradiusY: number = radiusX

        The vertical radius of the light.

      • Optionalcolor: string | Color = "#FFF"

        The color of the light at full intensity.

      • Optionalintensity: number = 0.7

        The peak alpha of the radial gradient at the light's center (0–1).

      Returns Light2d

    Properties

    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>
    
    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 (see renderer setBlendMode for available blend mode)

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

    the renderable physic body

    // 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);
    }

    ...

    }
    color: Color

    the color of the light

    "#FFF"
    
    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.

    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)

    illuminationOnly: boolean

    When true, this light acts as a pure illumination source — the gradient texture isn't drawn. The light still feeds the Stage ambient-cutout pass and the WebGL lit-sprite pipeline's per-frame uniforms, so normal-mapped sprites still get shaded by it. Use this for SpriteIlluminator-style demos where the light should be invisible (only its effect on normal-mapped surfaces is what you want to see).

    Default false, preserving the legacy "soft glowing spot" behavior.

    false
    
    indices: number[]

    a list of indices for all vertices composing this polygon

    intensity: number

    The intensity of the light

    0.7
    
    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
    
    lightHeight: number

    Light height above the sprite plane (Z axis), in the same units as radiusX/radiusY. Used by the WebGL lit-sprite pipeline as the Z component of the light direction in the dot(normal, lightDir) calculation: a low height makes the lighting graze across the surface (long visible shadows on normal-map detail), a high height makes it head-on (more uniform brightness on the lit hemisphere).

    Default is max(radiusX, radiusY) * 0.075 — a balanced look at the asset's native scale that prevents lights at the sprite's center from producing degenerate flat shading.

    Named lightHeight (not just height) to avoid colliding with the bbox-height getter Light2d inherits from Rect.

    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

    ""
    
    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!");
    }
    };
    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)];
    radiusX: number

    The horizontal radius of the light

    radiusY: number

    The vertical radius of the light

    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 centerX(): number

      the horizontal coordinate of this light's center. Overrides Rect's getter, which assumes pos is the bbox top-left and returns pos.x + width/2. Light2d uses anchorPoint = (0.5, 0.5), so pos already IS the center.

      Returns number

    • set centerX(value: number): void

      absolute center of this rectangle on the horizontal axis

      Parameters

      • value: number

      Returns void

    • 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

    Methods

    • 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
      }
    • draw this Light2d (automatically called by melonJS).

      Delegates to renderer.drawLight(this) — each renderer picks its own implementation (procedural shader on WebGL; cached Gradient rasterized into a shared CanvasRenderTarget on Canvas). Light2d itself doesn't know which path is used.

      Parameters

      Returns void

    • 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 a geometry representing the visible area of this light, in world-space coordinates (so it aligns with the rendered gradient regardless of camera scroll or container parenting).

      Returns Ellipse

      the light visible mask

    • 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

    • onCollision callback, triggered in case of collision, when this renderable body is colliding with another one

      Returns boolean

      true if the object should respond to the collision (its position and velocity will be corrected)

      // collision handler
      onCollision(response) {
      if (response.b.body.collisionType === me.collision.types.ENEMY_OBJECT) {
      // makes the other object solid, by substracting the overlap vector to the current position
      this.pos.sub(response.overlapV);
      this.hurt();
      // not solid
      return false;
      }
      // Make the object solid
      return true;
      },
    • 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

    • Set new radii for this light.

      Updates radiusX/radiusY and the underlying bbox (via Renderable.resize(width, height)) so getBounds() and getVisibleArea() — which feed the ambient-cutout pass — track the new size. The Canvas renderer's gradient cache auto-invalidates on next draw via its property comparison; the WebGL procedural shader adapts to the new dimensions automatically.

      Named setRadii (not resize) so it does not shadow Renderable.resize(width, height) — code that operates on a generic Renderable and calls .resize(w, h) keeps working when the instance happens to be a Light2d.

      Parameters

      • radiusX: number

        new horizontal radius

      • OptionalradiusY: number = radiusX

        new vertical radius

      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 Light2d

      this instance for object chaining