Back to Phaser

Phaser 4 -- Game Object Components Reference

skills/game-object-components/SKILL.md

4.1.022.2 KB
Original Source

Phaser 4 -- Game Object Components Reference

Component mixins that provide shared behavior to all Game Objects: Alpha, BlendMode, Depth, Flip, GetBounds, Lighting, Mask, Origin, ScrollFactor, Size, Texture, TextureCrop, Tint, Transform, Visible, PathFollower, RenderNodes, RenderSteps, Filters, FilterList.

Quick Start

js
// Every Game Object gets its component methods via mixins.
// Just call them directly on any game object:
const sprite = this.add.sprite(400, 300, 'hero');

sprite.setAlpha(0.5);                          // Alpha
sprite.setBlendMode(Phaser.BlendModes.ADD);    // BlendMode
sprite.setDepth(10);                           // Depth
sprite.setFlip(true, false);                   // Flip
sprite.setOrigin(0, 0);                        // Origin
sprite.setScrollFactor(0);                     // ScrollFactor (HUD)
sprite.setDisplaySize(64, 64);                 // Size
sprite.setTexture('hero', 'walk-1');           // Texture
sprite.setTint(0xff0000);                      // Tint
sprite.setPosition(100, 200);                  // Transform
sprite.setVisible(false);                      // Visible
sprite.setScale(2);                            // Transform
sprite.setAngle(45);                           // Transform

// Per-corner alpha (WebGL only)
sprite.setAlpha(1, 0.5, 0.5, 1);

// Crop a texture region
sprite.setCrop(0, 0, 32, 32);

// Enable WebGL filters (post-processing)
sprite.enableFilters();
sprite.filters.internal.addBlur(1, 2, 2, 1);

// Lighting (WebGL only, v4 feature)
sprite.setLighting(true);

Core Concepts

The Mixin System

Phaser uses Phaser.Class with a Mixins array to compose Game Objects from reusable component objects. Each component is a plain JS object whose properties and methods are copied onto the class prototype. This is NOT prototypal inheritance -- it is property copying at class definition time.

js
// How Phaser defines Sprite internally:
var Sprite = new Class({
    Extends: GameObject,
    Mixins: [
        Components.Alpha,
        Components.BlendMode,
        Components.Depth,
        Components.Flip,
        Components.GetBounds,
        Components.Lighting,
        Components.Mask,
        Components.Origin,
        Components.RenderNodes,
        Components.ScrollFactor,
        Components.Size,
        Components.TextureCrop,
        Components.Tint,
        Components.Transform,
        Components.Visible,
        SpriteRender
    ],
    initialize: function Sprite (scene, x, y, texture, frame) { /* ... */ }
});

Key Rules

  1. Components are mixed in at class creation, not per-instance.
  2. Most setter methods return this for chaining: sprite.setAlpha(0.5).setDepth(10).setPosition(100, 200).
  3. Many properties use getters/setters internally (e.g., alpha, depth, visible, scale, rotation). Setting alpha = 0 or scale = 0 clears render flags, skipping rendering.
  4. renderFlags is a bitmask: bit 0 = visible, bit 1 = alpha, bit 2 = scale, bit 3 = texture. All bits must be set for the object to render.
  5. Alpha vs AlphaSingle: Alpha supports per-corner alpha (WebGL), AlphaSingle only supports a single global alpha. Containers use AlphaSingle.
  6. Texture vs TextureCrop: TextureCrop extends Texture with setCrop() support. Sprites and Images use TextureCrop; some objects use plain Texture.
  7. Filters and RenderSteps are v4-only, WebGL-only systems for post-processing.

Complete Component Reference

Alpha

Provides per-corner transparency. Used by Sprite, Image, Text, and most renderable objects.

MemberTypeDescription
alphanumber (get/set)Global alpha 0-1. Setting this also sets all four corners. Setting to 0 disables rendering. Default: 1
alphaTopLeftnumber (get/set)Top-left corner alpha. WebGL only.
alphaTopRightnumber (get/set)Top-right corner alpha. WebGL only.
alphaBottomLeftnumber (get/set)Bottom-left corner alpha. WebGL only.
alphaBottomRightnumber (get/set)Bottom-right corner alpha. WebGL only.
setAlpha(topLeft?, topRight?, bottomLeft?, bottomRight?)methodSet alpha. One arg = uniform. Four args = per-corner (WebGL). Returns this.
clearAlpha()methodResets alpha to 1. Returns this.

AlphaSingle

Simplified alpha with no per-corner support. Used by Container.

MemberTypeDescription
alphanumber (get/set)Alpha 0-1. Default: 1
setAlpha(value?)methodSet alpha. Returns this.
clearAlpha()methodResets alpha to 1. Returns this.

BlendMode

Controls how pixels are composited during rendering.

MemberTypeDescription
blendModenumber/string (get/set)Current blend mode. Accepts Phaser.BlendModes const, string, or integer.
setBlendMode(value)methodSet the blend mode. Returns this.

WebGL blend modes: NORMAL, ADD, MULTIPLY, SCREEN, ERASE. Canvas supports additional browser-dependent modes.

Depth

Controls rendering order (z-index). Higher depth renders on top.

MemberTypeDescription
depthnumber (get/set)Depth value. Setting it queues a depth sort. Default: 0
setDepth(value)methodSet depth. Returns this.
setToTop()methodMove to top of display list (no depth change). Returns this.
setToBack()methodMove to back of display list. Returns this.
setAbove(gameObject)methodMove above another Game Object in display list. Returns this.
setBelow(gameObject)methodMove below another Game Object in display list. Returns this.

Flip

Visual mirroring without affecting physics bodies.

MemberTypeDescription
flipXbooleanHorizontal flip state. Default: false
flipYbooleanVertical flip state. Default: false
setFlipX(value)methodSet horizontal flip. Returns this.
setFlipY(value)methodSet vertical flip. Returns this.
setFlip(x, y)methodSet both flip states. Returns this.
toggleFlipX()methodToggle horizontal flip. Returns this.
toggleFlipY()methodToggle vertical flip. Returns this.
resetFlip()methodReset both to false. Returns this.

GetBounds

Calculate positions and bounding rectangles regardless of origin.

MemberTypeDescription
getCenter(output?, includeParent?)methodCenter coordinate. Returns Vector2Like.
getTopLeft(output?, includeParent?)methodTop-left coordinate. Returns Vector2Like.
getTopCenter(output?, includeParent?)methodTop-center coordinate. Returns Vector2Like.
getTopRight(output?, includeParent?)methodTop-right coordinate. Returns Vector2Like.
getLeftCenter(output?, includeParent?)methodLeft-center coordinate. Returns Vector2Like.
getRightCenter(output?, includeParent?)methodRight-center coordinate. Returns Vector2Like.
getBottomLeft(output?, includeParent?)methodBottom-left coordinate. Returns Vector2Like.
getBottomCenter(output?, includeParent?)methodBottom-center coordinate. Returns Vector2Like.
getBottomRight(output?, includeParent?)methodBottom-right coordinate. Returns Vector2Like.
getBounds(output?)methodFull bounding rectangle. Returns Rectangle.

Set includeParent = true to factor in parent Container transforms.

Lighting (v4, WebGL only)

Enables light-based rendering with the Phaser 4 lighting system.

MemberTypeDescription
lightingbooleanWhether to use lighting. Default: false
selfShadowobject{ enabled, penumbra, diffuseFlatThreshold }. Self-shadow settings.
setLighting(enable)methodEnable/disable lighting. Returns this.
setSelfShadow(enabled?, penumbra?, diffuseFlatThreshold?)methodConfigure self-shadow. Pass null for enabled to use game config default. Returns this.

Mask (Canvas only in v4)

Geometry masking for Canvas renderer. In WebGL, use Filters.addMask() instead.

MemberTypeDescription
maskGeometryMaskThe current mask, or null.
setMask(mask)methodApply a GeometryMask. Canvas only. In WebGL, logs a warning. Returns this.
clearMask(destroyMask?)methodRemove the mask. Pass true to also destroy it. Returns this.
createGeometryMask(graphics?)methodCreate a GeometryMask from a Graphics/Shape object. Returns GeometryMask.

Origin

Controls the anchor point for position, rotation, and scale. Normalized 0-1.

MemberTypeDescription
originXnumberHorizontal origin. Default: 0.5 (center)
originYnumberVertical origin. Default: 0.5 (center)
displayOriginXnumber (get/set)Origin in pixels. Setting recalculates originX.
displayOriginYnumber (get/set)Origin in pixels. Setting recalculates originY.
setOrigin(x?, y?)methodSet origin (normalized). y defaults to x. Default: 0.5. Returns this.
setOriginFromFrame()methodSet origin from texture Frame pivot. Returns this.
setDisplayOrigin(x?, y?)methodSet origin in pixels. Returns this.
updateDisplayOrigin()methodRecalculate display origin cache. Returns this.

ScrollFactor

Controls how camera scrolling affects the object's rendered position.

MemberTypeDescription
scrollFactorXnumberHorizontal scroll factor. Default: 1
scrollFactorYnumberVertical scroll factor. Default: 1
setScrollFactor(x, y?)methodSet scroll factor. y defaults to x. Returns this.

Key values: 0 = fixed to camera (HUD element), 1 = moves with camera, 0.5 = parallax half-speed.

Size

Manages native and display dimensions.

MemberTypeDescription
widthnumberNative (un-scaled) width.
heightnumberNative (un-scaled) height.
displayWidthnumber (get/set)Scaled width. Setting adjusts scaleX.
displayHeightnumber (get/set)Scaled height. Setting adjusts scaleY.
setSize(width, height)methodSet native size. Does NOT affect rendered size. Returns this.
setDisplaySize(width, height)methodSet rendered size (adjusts scale). Returns this.
setSizeToFrame(frame?)methodSet size from a texture Frame. Returns this.

Texture

Gets and sets the texture and frame for rendering.

MemberTypeDescription
texturePhaser.Textures.TextureThe current Texture.
framePhaser.Textures.FrameThe current Frame.
setTexture(key, frame?, updateSize?, updateOrigin?)methodSet texture by key. Returns this.
setFrame(frame, updateSize?, updateOrigin?)methodSet frame by name, index, or Frame instance. Updates size and origin by default. Returns this.

TextureCrop

Extends Texture with cropping support. Used by Sprite and Image.

MemberTypeDescription
texturePhaser.Textures.TextureThe current Texture.
framePhaser.Textures.FrameThe current Frame.
isCroppedbooleanWhether cropping is active.
setTexture(key, frame?)methodSet texture by key. Returns this.
setFrame(frame, updateSize?, updateOrigin?)methodSet frame. Also updates crop UVs if cropped. Returns this.
setCrop(x?, y?, width?, height?)methodSet crop rectangle. Pass no args to clear. Accepts a Rectangle as first arg. Returns this.

Tint (WebGL only)

Applies color tinting to the texture via per-corner vertex colors.

MemberTypeDescription
tintnumber (get/set)Uniform tint color (reads tintTopLeft). Default: 0xffffff
tintTopLeftnumberTop-left vertex tint. Default: 0xffffff
tintTopRightnumberTop-right vertex tint. Default: 0xffffff
tintBottomLeftnumberBottom-left vertex tint. Default: 0xffffff
tintBottomRightnumberBottom-right vertex tint. Default: 0xffffff
tintModenumberTint blend mode. Default: Phaser.TintModes.MULTIPLY
isTintedboolean (readonly)True if any tint or mode is set.
setTint(topLeft?, topRight?, bottomLeft?, bottomRight?)methodSet tint colors. One arg = uniform. Returns this.
setTintMode(mode)methodSet tint mode (v4). Modes: MULTIPLY, FILL, ADD, SCREEN, OVERLAY, HARD_LIGHT. Returns this.
clearTint()methodReset to white + MULTIPLY. Returns this.

v4 change: setTintFill() is removed. Use setTint(color).setTintMode(Phaser.TintModes.FILL) instead.

Transform

Position, scale, rotation, and coordinate transforms.

MemberTypeDescription
xnumberX position. Default: 0
ynumberY position. Default: 0
znumberZ position (NOT rendering order; use depth). Default: 0
wnumberW position. Default: 0
scalenumber (get/set)Uniform scale. Get returns average of scaleX and scaleY.
scaleXnumber (get/set)Horizontal scale. Default: 1
scaleYnumber (get/set)Vertical scale. Default: 1
anglenumber (get/set)Rotation in degrees (clockwise, 0 = right).
rotationnumber (get/set)Rotation in radians.
setPosition(x?, y?, z?, w?)methodSet position. y defaults to x. Returns this.
copyPosition(source)methodCopy x/y/z/w from a Vector-like object. Returns this.
setRandomPosition(x?, y?, width?, height?)methodRandomize position within area. Returns this.
setRotation(radians?)methodSet rotation in radians. Returns this.
setAngle(degrees?)methodSet rotation in degrees. Returns this.
setScale(x?, y?)methodSet scale. y defaults to x. Returns this.
setX(value?)methodSet x. Returns this.
setY(value?)methodSet y. Returns this.
setZ(value?)methodSet z. Returns this.
setW(value?)methodSet w. Returns this.
getLocalTransformMatrix(tempMatrix?)methodGet local transform matrix. Returns TransformMatrix.
getWorldTransformMatrix(tempMatrix?, parentMatrix?)methodGet world transform including parent Containers. Returns TransformMatrix.
getLocalPoint(x, y, point?, camera?)methodConvert world coords to local space. Returns Vector2.
getWorldPoint(point?, tempMatrix?, parentMatrix?)methodGet world position factoring parent containers. Returns Vector2.
getParentRotation()methodSum of all parent container rotations in radians.

Visible

Controls whether the Game Object renders. Invisible objects still run update logic.

MemberTypeDescription
visibleboolean (get/set)Visibility state. Default: true
setVisible(value)methodSet visibility. Returns this.

PathFollower

Manages following a Phaser.Curves.Path using an internal tween.

MemberTypeDescription
pathPhaser.Curves.PathThe Path being followed.
rotateToPathbooleanAuto-rotate to face path direction. Default: false
pathRotationOffsetnumberRotation offset in degrees when rotateToPath is true.
pathOffsetVector2Position offset from path coordinates.
pathVectorVector2Current point on the path.
pathDeltaVector2Distance traveled since last update.
pathTweenTweenThe tween driving path movement.
setPath(path, config?)methodSet a new Path. Returns this.
setRotateToPath(value, offset?)methodEnable auto-rotation. Returns this.
isFollowing()methodReturns true if actively following.
startFollow(config?, startAt?)methodStart following. config can be duration (number) or PathConfig. Returns this.
pauseFollow()methodPause movement. Returns this.
resumeFollow()methodResume movement. Returns this.
stopFollow()methodStop following. Returns this.

RenderNodes, RenderSteps, Filters, FilterList (v4, WebGL only)

For RenderNodes, RenderSteps, and FilterList details, see the filters-and-postfx skill and references/REFERENCE.md.

Key points: Call enableFilters() on game objects before accessing filters. Cameras have filters by default. Use filters.internal for object-local effects and filters.external for screen-space effects.

For a full component-to-game-object matrix, see references/REFERENCE.md.

Factory Registration and Display List

Custom Game Object Factory Registration

Register custom game objects on the factory so they can be created via this.add.myObject():

js
class LaserBeam extends Phaser.GameObjects.Sprite {
    constructor(scene, x, y) {
        super(scene, x, y, 'laser');
    }
}

Phaser.GameObjects.GameObjectFactory.register('laserBeam', function (x, y) {
    const beam = new LaserBeam(this.scene, x, y);
    this.displayList.add(beam);
    return beam;
});

// Now usable in any scene:
const laser = this.add.laserBeam(100, 200);

Factory (this.add) vs Creator (this.make)

this.add creates the object AND adds it to the display list. this.make creates the object but does NOT add it -- useful for off-screen preparation or deferred display.

js
// Added to display list immediately
const visible = this.add.sprite(100, 100, 'hero');

// Created but NOT on the display list
const offscreen = this.make.sprite({ key: 'hero', x: 100, y: 100 });

// Add it later when ready
this.add.existing(offscreen);

GetAdvancedValue for Flexible Config

GetAdvancedValue resolves static values, random arrays, randInt/Float ranges, and callbacks from config objects:

js
// Static value
{ speed: 100 }

// Random from array
{ speed: [100, 200, 300] }

// Random integer range
{ speed: { randInt: [50, 150] } }

// Random float range
{ speed: { randFloat: [0.5, 1.5] } }

// Callback
{ speed: function () { return Math.random() * 100; } }

Display List Ordering

Objects added later render on top of earlier objects. Control ordering with:

js
// Depth-based ordering (higher = on top, triggers sort)
sprite.setDepth(10);

// Display list position (no depth change)
sprite.setToTop();
sprite.setToBack();
sprite.setAbove(otherSprite);
sprite.setBelow(otherSprite);

When both depth and display list position are used, depth takes priority after the next sort pass.

Gotchas

  1. alpha=0 prevents rendering entirely: Setting alpha to 0 clears a render flag bit. The object is not drawn at all, not merely transparent. Same applies to scale = 0 and visible = false.

  2. Flip does not affect physics: Flipping is rendering-only. Physics bodies remain unchanged. Account for this in collision code.

  3. ScrollFactor and physics: Physics collisions use world position. A scroll factor other than 1 offsets where the texture renders but not where the body is. For HUD elements with scroll factor 0, avoid adding physics bodies.

  4. depth vs display list order: setDepth() queues a sort and is the primary z-ordering tool. setToTop(), setAbove(), etc. reorder the display list without changing depth. If you mix both, depth takes priority after the next sort.

  5. Mask component is Canvas-only in v4: For WebGL masking, use enableFilters() then filters.internal.addMask(). The setMask() method logs a warning in WebGL.

  6. setTintFill is removed in v4: Use setTint(color).setTintMode(Phaser.TintModes.FILL) instead.

  7. Tint modes in v4: Tint mode is now separate from tint color. Available modes: MULTIPLY (default), FILL, ADD, SCREEN, OVERLAY, HARD_LIGHT.

  8. displayWidth/displayHeight adjusts scale: Setting displayWidth or displayHeight modifies scaleX/scaleY. It does NOT change width/height.

  9. setSize vs setDisplaySize: setSize() changes internal dimensions (used for frames, physics). setDisplaySize() changes the rendered size by adjusting scale.

  10. Origin default is 0.5: All Game Objects default to center origin. Use setOrigin(0, 0) for top-left positioning. Text and BitmapText instead default to top-left positioning.

  11. Transform.z is NOT depth: The z property on Transform is for custom use. Rendering order is controlled by depth (Depth component) or display list position.

  12. Filters are expensive: Each object with active filters requires extra draw calls. Use renderFilters = false to temporarily disable. Internal filters are cheaper than external.

Source File Map

FileDescription
src/gameobjects/components/index.jsComponent registry, exports all components
src/gameobjects/components/Alpha.jsPer-corner alpha mixin
src/gameobjects/components/AlphaSingle.jsSingle-value alpha mixin
src/gameobjects/components/BlendMode.jsBlend mode mixin
src/gameobjects/components/Depth.jsDepth/z-order mixin
src/gameobjects/components/Flip.jsVisual flip mixin
src/gameobjects/components/GetBounds.jsBounds calculation mixin
src/gameobjects/components/Lighting.jsv4 lighting mixin
src/gameobjects/components/Mask.jsCanvas geometry mask mixin
src/gameobjects/components/Origin.jsOrigin/anchor mixin
src/gameobjects/components/ScrollFactor.jsCamera scroll factor mixin
src/gameobjects/components/Size.jsDimensions mixin
src/gameobjects/components/Texture.jsTexture/frame assignment mixin
src/gameobjects/components/TextureCrop.jsTexture with crop support mixin
src/gameobjects/components/Tint.jsVertex color tinting mixin
src/gameobjects/components/Transform.jsPosition/scale/rotation mixin
src/gameobjects/components/Visible.jsVisibility mixin
src/gameobjects/components/PathFollower.jsPath-following mixin
src/gameobjects/components/RenderNodes.jsv4 WebGL render node mixin
src/gameobjects/components/RenderSteps.jsv4 WebGL render step mixin
src/gameobjects/components/Filters.jsv4 WebGL filter system mixin
src/gameobjects/components/FilterList.jsv4 filter list class (add effects)
src/gameobjects/components/TransformMatrix.js2D transform matrix utility

Related skills: sprites-and-images.md, custom-game-objects.md