game-object-components

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Phaser 4 -- Game Object Components Reference

Phaser 4 -- 游戏对象组件参考文档

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.
为所有游戏对象提供共享行为的组件Mixin: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);
js
// 每个游戏对象都通过Mixin获取组件方法。
// 直接在任意游戏对象上调用这些方法即可:
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(变换)

// 四角独立透明度(仅WebGL支持)
sprite.setAlpha(1, 0.5, 0.5, 1);

// 裁剪纹理区域
sprite.setCrop(0, 0, 32, 32);

// 启用WebGL滤镜(后期处理)
sprite.enableFilters();
sprite.filters.internal.addBlur(1, 2, 2, 1);

// 光照系统(仅WebGL支持,Phaser 4新特性)
sprite.setLighting(true);

Core Concepts

核心概念

The Mixin System

Mixin系统

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) { /* ... */ }
});
Phaser 使用
Phaser.Class
结合
Mixins
数组,通过可复用的组件对象来组合游戏对象。每个组件是一个普通JS对象,其属性和方法会被复制到类原型上。这不是原型继承,而是在类定义阶段进行属性复制。
js
// Phaser内部定义Sprite的方式:
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.
  1. 组件在类创建时混入,而非每个实例单独混入。
  2. 大多数setter方法返回
    this
    以支持链式调用:
    sprite.setAlpha(0.5).setDepth(10).setPosition(100, 200)
  3. 许多属性内部使用getter/setter(如
    alpha
    depth
    visible
    scale
    rotation
    )。设置
    alpha = 0
    scale = 0
    会清除渲染标志位,从而跳过渲染。
  4. renderFlags
    是一个位掩码:第0位=可见性,第1位=透明度,第2位=缩放,第3位=纹理。所有位都设置时对象才会被渲染。
  5. Alpha与AlphaSingle
    Alpha
    支持四角独立透明度(WebGL),
    AlphaSingle
    仅支持全局单一透明度。容器类使用
    AlphaSingle
  6. Texture与TextureCrop
    TextureCrop
    扩展了
    Texture
    ,增加了
    setCrop()
    支持。Sprite和Image使用
    TextureCrop
    ;部分对象使用基础版
    Texture
  7. Filters和RenderSteps是Phaser 4独有的特性,仅支持WebGL,用于后期处理。

Complete Component Reference

完整组件参考

Alpha

Alpha

Provides per-corner transparency. Used by Sprite, Image, Text, and most renderable objects.
MemberTypeDescription
alpha
number (get/set)Global alpha 0-1. Setting this also sets all four corners. Setting to 0 disables rendering. Default:
1
alphaTopLeft
number (get/set)Top-left corner alpha. WebGL only.
alphaTopRight
number (get/set)Top-right corner alpha. WebGL only.
alphaBottomLeft
number (get/set)Bottom-left corner alpha. WebGL only.
alphaBottomRight
number (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
.
提供四角独立透明度控制。适用于Sprite、Image、Text及大多数可渲染对象。
成员类型描述
alpha
数字类型(可读写)全局透明度,范围0-1。设置该值会同时设置四个角的透明度。设为0时会禁用渲染。默认值:
1
alphaTopLeft
数字类型(可读写)左上角透明度,仅WebGL支持。
alphaTopRight
数字类型(可读写)右上角透明度,仅WebGL支持。
alphaBottomLeft
数字类型(可读写)左下角透明度,仅WebGL支持。
alphaBottomRight
数字类型(可读写)右下角透明度,仅WebGL支持。
setAlpha(topLeft?, topRight?, bottomLeft?, bottomRight?)
方法设置透明度。传入1个参数=全局统一值;传入4个参数=四角独立设置(仅WebGL)。返回
this
clearAlpha()
方法将透明度重置为1。返回
this

AlphaSingle

AlphaSingle

Simplified alpha with no per-corner support. Used by Container.
MemberTypeDescription
alpha
number (get/set)Alpha 0-1. Default:
1
setAlpha(value?)
methodSet alpha. Returns
this
.
clearAlpha()
methodResets alpha to 1. Returns
this
.
简化版透明度控制,不支持四角独立设置。适用于容器类。
成员类型描述
alpha
数字类型(可读写)透明度,范围0-1。默认值:
1
setAlpha(value?)
方法设置透明度。返回
this
clearAlpha()
方法将透明度重置为1。返回
this

BlendMode

BlendMode

Controls how pixels are composited during rendering.
MemberTypeDescription
blendMode
number/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.
控制渲染时像素的合成方式。
成员类型描述
blendMode
数字/字符串类型(可读写)当前混合模式。支持
Phaser.BlendModes
常量、字符串或整数。
setBlendMode(value)
方法设置混合模式。返回
this
WebGL支持的混合模式:
NORMAL
ADD
MULTIPLY
SCREEN
ERASE
。Canvas支持更多浏览器相关模式。

Depth

Depth

Controls rendering order (z-index). Higher depth renders on top.
MemberTypeDescription
depth
number (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
.
控制渲染顺序(z轴层级)。值越高,渲染层级越靠上。
成员类型描述
depth
数字类型(可读写)深度值。设置该值会触发深度排序。默认值:
0
setDepth(value)
方法设置深度。返回
this
setToTop()
方法移至显示列表顶部(不改变depth值)。返回
this
setToBack()
方法移至显示列表底部。返回
this
setAbove(gameObject)
方法移至另一个游戏对象上方。返回
this
setBelow(gameObject)
方法移至另一个游戏对象下方。返回
this

Flip

Flip

Visual mirroring without affecting physics bodies.
MemberTypeDescription
flipX
booleanHorizontal flip state. Default:
false
flipY
booleanVertical 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
.
视觉镜像翻转,不影响物理体。
成员类型描述
flipX
布尔值水平翻转状态。默认值:
false
flipY
布尔值垂直翻转状态。默认值:
false
setFlipX(value)
方法设置水平翻转。返回
this
setFlipY(value)
方法设置垂直翻转。返回
this
setFlip(x, y)
方法同时设置水平和垂直翻转状态。返回
this
toggleFlipX()
方法切换水平翻转状态。返回
this
toggleFlipY()
方法切换垂直翻转状态。返回
this
resetFlip()
方法将两个翻转状态重置为false。返回
this

GetBounds

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.
计算对象的位置和边界矩形,不受原点影响。
成员类型描述
getCenter(output?, includeParent?)
方法获取中心坐标。返回
Vector2Like
类型。
getTopLeft(output?, includeParent?)
方法获取左上角坐标。返回
Vector2Like
类型。
getTopCenter(output?, includeParent?)
方法获取顶部中心坐标。返回
Vector2Like
类型。
getTopRight(output?, includeParent?)
方法获取右上角坐标。返回
Vector2Like
类型。
getLeftCenter(output?, includeParent?)
方法获取左侧中心坐标。返回
Vector2Like
类型。
getRightCenter(output?, includeParent?)
方法获取右侧中心坐标。返回
Vector2Like
类型。
getBottomLeft(output?, includeParent?)
方法获取左下角坐标。返回
Vector2Like
类型。
getBottomCenter(output?, includeParent?)
方法获取底部中心坐标。返回
Vector2Like
类型。
getBottomRight(output?, includeParent?)
方法获取右下角坐标。返回
Vector2Like
类型。
getBounds(output?)
方法获取完整边界矩形。返回
Rectangle
类型。
设置
includeParent = true
时,会计算父容器的变换影响。

Lighting (v4, WebGL only)

Lighting(Phaser 4,仅WebGL支持)

Enables light-based rendering with the Phaser 4 lighting system.
MemberTypeDescription
lighting
booleanWhether to use lighting. Default:
false
selfShadow
object
{ 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
.
启用Phaser 4光照系统的基于光照的渲染。
成员类型描述
lighting
布尔值是否启用光照。默认值:
false
selfShadow
对象自阴影设置,包含
{ enabled, penumbra, diffuseFlatThreshold }
setLighting(enable)
方法启用/禁用光照。返回
this
setSelfShadow(enabled?, penumbra?, diffuseFlatThreshold?)
方法配置自阴影。若
enabled
传null,则使用游戏配置的默认值。返回
this

Mask (Canvas only in v4)

Mask(Phaser 4中仅Canvas支持)

Geometry masking for Canvas renderer. In WebGL, use
Filters.addMask()
instead.
MemberTypeDescription
mask
GeometryMaskThe 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
.
Canvas渲染器的几何遮罩。WebGL环境下,请使用
Filters.addMask()
替代。
成员类型描述
mask
GeometryMask当前遮罩对象,若无则为null。
setMask(mask)
方法应用GeometryMask。仅Canvas支持,WebGL环境下会打印警告。返回
this
clearMask(destroyMask?)
方法移除遮罩。传
true
会同时销毁遮罩对象。返回
this
createGeometryMask(graphics?)
方法从Graphics/Shape对象创建GeometryMask。返回
GeometryMask
类型。

Origin

Origin

Controls the anchor point for position, rotation, and scale. Normalized 0-1.
MemberTypeDescription
originX
numberHorizontal origin. Default:
0.5
(center)
originY
numberVertical origin. Default:
0.5
(center)
displayOriginX
number (get/set)Origin in pixels. Setting recalculates
originX
.
displayOriginY
number (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
.
控制位置、旋转和缩放的锚点。范围0-1(归一化值)。
成员类型描述
originX
数字类型水平原点。默认值:
0.5
(中心)
originY
数字类型垂直原点。默认值:
0.5
(中心)
displayOriginX
数字类型(可读写)像素单位的原点。设置该值会重新计算
originX
displayOriginY
数字类型(可读写)像素单位的原点。设置该值会重新计算
originY
setOrigin(x?, y?)
方法设置归一化原点。
y
默认等于
x
。默认值:
0.5
。返回
this
setOriginFromFrame()
方法根据纹理Frame的中心点设置原点。返回
this
setDisplayOrigin(x?, y?)
方法设置像素单位的原点。返回
this
updateDisplayOrigin()
方法重新计算显示原点缓存。返回
this

ScrollFactor

ScrollFactor

Controls how camera scrolling affects the object's rendered position.
MemberTypeDescription
scrollFactorX
numberHorizontal scroll factor. Default:
1
scrollFactorY
numberVertical 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.
控制相机滚动对对象渲染位置的影响。
成员类型描述
scrollFactorX
数字类型水平滚动因子。默认值:
1
scrollFactorY
数字类型垂直滚动因子。默认值:
1
setScrollFactor(x, y?)
方法设置滚动因子。
y
默认等于
x
。返回
this
关键取值:
0
= 固定在相机上(HUD元素),
1
= 随相机移动,
0.5
= 半速视差效果。

Size

Size

Manages native and display dimensions.
MemberTypeDescription
width
numberNative (un-scaled) width.
height
numberNative (un-scaled) height.
displayWidth
number (get/set)Scaled width. Setting adjusts
scaleX
.
displayHeight
number (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
.
管理原生尺寸和显示尺寸。
成员类型描述
width
数字类型原生(未缩放)宽度。
height
数字类型原生(未缩放)高度。
displayWidth
数字类型(可读写)缩放后的宽度。设置该值会调整
scaleX
displayHeight
数字类型(可读写)缩放后的高度。设置该值会调整
scaleY
setSize(width, height)
方法设置原生尺寸。不影响渲染尺寸。返回
this
setDisplaySize(width, height)
方法设置渲染尺寸(通过调整缩放实现)。返回
this
setSizeToFrame(frame?)
方法根据纹理Frame设置尺寸。返回
this

Texture

Texture

Gets and sets the texture and frame for rendering.
MemberTypeDescription
texture
Phaser.Textures.TextureThe current Texture.
frame
Phaser.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
.
获取和设置渲染用的纹理及帧。
成员类型描述
texture
Phaser.Textures.Texture当前纹理对象。
frame
Phaser.Textures.Frame当前帧对象。
setTexture(key, frame?, updateSize?, updateOrigin?)
方法通过键名设置纹理。返回
this
setFrame(frame, updateSize?, updateOrigin?)
方法通过名称、索引或Frame实例设置帧。默认会更新尺寸和原点。返回
this

TextureCrop

TextureCrop

Extends Texture with cropping support. Used by Sprite and Image.
MemberTypeDescription
texture
Phaser.Textures.TextureThe current Texture.
frame
Phaser.Textures.FrameThe current Frame.
isCropped
booleanWhether 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
.
扩展Texture组件,增加裁剪支持。适用于Sprite和Image。
成员类型描述
texture
Phaser.Textures.Texture当前纹理对象。
frame
Phaser.Textures.Frame当前帧对象。
isCropped
布尔值是否启用裁剪。
setTexture(key, frame?)
方法通过键名设置纹理。返回
this
setFrame(frame, updateSize?, updateOrigin?)
方法设置帧。若已启用裁剪,会同时更新裁剪UV坐标。返回
this
setCrop(x?, y?, width?, height?)
方法设置裁剪矩形。不传参数则清除裁剪。支持传入
Rectangle
对象作为第一个参数。返回
this

Tint (WebGL only)

Tint(仅WebGL支持)

Applies color tinting to the texture via per-corner vertex colors.
MemberTypeDescription
tint
number (get/set)Uniform tint color (reads
tintTopLeft
). Default:
0xffffff
tintTopLeft
numberTop-left vertex tint. Default:
0xffffff
tintTopRight
numberTop-right vertex tint. Default:
0xffffff
tintBottomLeft
numberBottom-left vertex tint. Default:
0xffffff
tintBottomRight
numberBottom-right vertex tint. Default:
0xffffff
tintMode
numberTint blend mode. Default:
Phaser.TintModes.MULTIPLY
isTinted
boolean (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.
通过四角顶点颜色为纹理应用着色。
成员类型描述
tint
数字类型(可读写)全局着色颜色(读取
tintTopLeft
的值)。默认值:
0xffffff
tintTopLeft
数字类型左上角顶点着色。默认值:
0xffffff
tintTopRight
数字类型右上角顶点着色。默认值:
0xffffff
tintBottomLeft
数字类型左下角顶点着色。默认值:
0xffffff
tintBottomRight
数字类型右下角顶点着色。默认值:
0xffffff
tintMode
数字类型着色混合模式。默认值:
Phaser.TintModes.MULTIPLY
isTinted
布尔值(只读)若设置了任何着色或模式,则为true。
setTint(topLeft?, topRight?, bottomLeft?, bottomRight?)
方法设置着色颜色。传入1个参数=全局统一值。返回
this
setTintMode(mode)
方法设置着色模式(Phaser 4特性)。支持模式:
MULTIPLY
FILL
ADD
SCREEN
OVERLAY
HARD_LIGHT
。返回
this
clearTint()
方法重置为白色+MULTIPLY模式。返回
this
Phaser 4变更
setTintFill()
已移除,请使用
setTint(color).setTintMode(Phaser.TintModes.FILL)
替代。

Transform

Transform

Position, scale, rotation, and coordinate transforms.
MemberTypeDescription
x
numberX position. Default:
0
y
numberY position. Default:
0
z
numberZ position (NOT rendering order; use
depth
). Default:
0
w
numberW position. Default:
0
scale
number (get/set)Uniform scale. Get returns average of scaleX and scaleY.
scaleX
number (get/set)Horizontal scale. Default:
1
scaleY
number (get/set)Vertical scale. Default:
1
angle
number (get/set)Rotation in degrees (clockwise, 0 = right).
rotation
number (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.
位置、缩放、旋转和坐标变换。
成员类型描述
x
数字类型X轴位置。默认值:
0
y
数字类型Y轴位置。默认值:
0
z
数字类型Z轴位置(不控制渲染顺序,渲染顺序请用
depth
)。默认值:
0
w
数字类型W轴位置。默认值:
0
scale
数字类型(可读写)统一缩放比例。读取时返回scaleX和scaleY的平均值。
scaleX
数字类型(可读写)水平缩放比例。默认值:
1
scaleY
数字类型(可读写)垂直缩放比例。默认值:
1
angle
数字类型(可读写)旋转角度(顺时针,0=向右)。
rotation
数字类型(可读写)旋转弧度。
setPosition(x?, y?, z?, w?)
方法设置位置。
y
默认等于
x
。返回
this
copyPosition(source)
方法从类Vector对象复制x/y/z/w值。返回
this
setRandomPosition(x?, y?, width?, height?)
方法在指定区域内随机设置位置。返回
this
setRotation(radians?)
方法设置旋转弧度。返回
this
setAngle(degrees?)
方法设置旋转角度。返回
this
setScale(x?, y?)
方法设置缩放比例。
y
默认等于
x
。返回
this
setX(value?)
方法设置X轴位置。返回
this
setY(value?)
方法设置Y轴位置。返回
this
setZ(value?)
方法设置Z轴位置。返回
this
setW(value?)
方法设置W轴位置。返回
this
getLocalTransformMatrix(tempMatrix?)
方法获取本地变换矩阵。返回
TransformMatrix
类型。
getWorldTransformMatrix(tempMatrix?, parentMatrix?)
方法获取包含父容器的全局变换矩阵。返回
TransformMatrix
类型。
getLocalPoint(x, y, point?, camera?)
方法将世界坐标转换为本地坐标。返回
Vector2
类型。
getWorldPoint(point?, tempMatrix?, parentMatrix?)
方法获取包含父容器影响的全局位置。返回
Vector2
类型。
getParentRotation()
方法获取所有父容器的旋转弧度总和。

Visible

Visible

Controls whether the Game Object renders. Invisible objects still run update logic.
MemberTypeDescription
visible
boolean (get/set)Visibility state. Default:
true
setVisible(value)
methodSet visibility. Returns
this
.
控制游戏对象是否渲染。不可见对象仍会运行更新逻辑。
成员类型描述
visible
布尔值(可读写)可见性状态。默认值:
true
setVisible(value)
方法设置可见性。返回
this

PathFollower

PathFollower

Manages following a
Phaser.Curves.Path
using an internal tween.
MemberTypeDescription
path
Phaser.Curves.PathThe Path being followed.
rotateToPath
booleanAuto-rotate to face path direction. Default:
false
pathRotationOffset
numberRotation offset in degrees when
rotateToPath
is true.
pathOffset
Vector2Position offset from path coordinates.
pathVector
Vector2Current point on the path.
pathDelta
Vector2Distance traveled since last update.
pathTween
TweenThe 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
.
通过内部补间动画管理
Phaser.Curves.Path
的跟随行为。
成员类型描述
path
Phaser.Curves.Path正在跟随的路径对象。
rotateToPath
布尔值是否自动旋转以面向路径方向。默认值:
false
pathRotationOffset
数字类型
rotateToPath
为true时的旋转偏移角度(度)。
pathOffset
Vector2相对于路径坐标的位置偏移。
pathVector
Vector2路径上的当前点。
pathDelta
Vector2自上次更新以来移动的距离。
pathTween
Tween驱动路径移动的补间动画。
setPath(path, config?)
方法设置新路径。返回
this
setRotateToPath(value, offset?)
方法启用自动旋转。返回
this
isFollowing()
方法若正在跟随路径则返回
true
startFollow(config?, startAt?)
方法开始跟随路径。
config
可以是时长(数字)或PathConfig对象。返回
this
pauseFollow()
方法暂停移动。返回
this
resumeFollow()
方法恢复移动。返回
this
stopFollow()
方法停止跟随路径。返回
this

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

RenderNodes、RenderSteps、Filters、FilterList(Phaser 4,仅WebGL支持)

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.
关于RenderNodes、RenderSteps和FilterList的详细信息,请参考filters-and-postfx技能文档references/REFERENCE.md
关键点:在访问
filters
之前,需先调用游戏对象的
enableFilters()
。相机默认启用滤镜。使用
filters.internal
添加对象本地特效,使用
filters.external
添加屏幕空间特效。
组件与游戏对象的对应矩阵,请参考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);
将自定义游戏对象注册到工厂,即可通过
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;
});

// 现在可在任意场景中使用:
const laser = this.add.laserBeam(100, 200);

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

Factory(this.add)与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);
this.add
创建对象并将其添加到显示列表。
this.make
仅创建对象,不添加到显示列表——适用于屏幕外准备或延迟显示的场景。
js
// 立即添加到显示列表
const visible = this.add.sprite(100, 100, 'hero');

// 创建但不添加到显示列表
const offscreen = this.make.sprite({ key: 'hero', x: 100, y: 100 });

// 准备好后再添加
this.add.existing(offscreen);

GetAdvancedValue for Flexible Config

使用GetAdvancedValue实现灵活配置

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; } }
GetAdvancedValue
可解析配置对象中的静态值、随机数组、randInt/Float范围及回调函数:
js
// 静态值
{ speed: 100 }

// 从数组中随机选择
{ speed: [100, 200, 300] }

// 随机整数范围
{ speed: { randInt: [50, 150] } }

// 随机浮点数范围
{ speed: { randFloat: [0.5, 1.5] } }

// 回调函数
{ 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.
后添加的对象会渲染在先添加对象的上方。可通过以下方式控制排序:
js
// 基于深度的排序(值越高越靠上,触发排序)
sprite.setDepth(10);

// 调整显示列表位置(不改变depth值)
sprite.setToTop();
sprite.setToBack();
sprite.setAbove(otherSprite);
sprite.setBelow(otherSprite);
当同时使用
depth
和显示列表位置时,下次排序后
depth
优先级更高。

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.
  1. alpha=0会完全阻止渲染:将
    alpha
    设为0会清除一个渲染标志位。对象不会被绘制,而不仅仅是透明。
    scale = 0
    visible = false
    也会有同样的效果。
  2. Flip不影响物理系统:翻转仅作用于视觉渲染,物理体不会改变。在碰撞检测代码中需考虑这一点。
  3. ScrollFactor与物理系统:物理碰撞使用世界位置。滚动因子不为1时,会偏移纹理渲染位置,但不会改变物理体位置。对于滚动因子为0的HUD元素,建议不要添加物理体。
  4. depth与显示列表顺序
    setDepth()
    会触发排序,是控制z轴层级的主要工具。
    setToTop()
    setAbove()
    等方法仅调整显示列表位置,不改变
    depth
    。若同时使用两者,下次排序后
    depth
    优先级更高。
  5. Mask组件在Phaser 4中仅支持Canvas:WebGL环境下的遮罩,请先调用
    enableFilters()
    ,再使用
    filters.internal.addMask()
    。WebGL环境下调用
    setMask()
    会打印警告。
  6. setTintFill在Phaser 4中已移除:请使用
    setTint(color).setTintMode(Phaser.TintModes.FILL)
    替代。
  7. Phaser 4中的着色模式:着色模式现在与着色颜色分离。支持模式:
    MULTIPLY
    (默认)、
    FILL
    ADD
    SCREEN
    OVERLAY
    HARD_LIGHT
  8. displayWidth/displayHeight会调整缩放比例:设置
    displayWidth
    displayHeight
    会修改
    scaleX
    /
    scaleY
    ,不会改变
    width
    /
    height
  9. setSize与setDisplaySize的区别
    setSize()
    改变内部尺寸(用于帧、物理系统)。
    setDisplaySize()
    通过调整缩放比例改变渲染尺寸。
  10. Origin默认值为0.5:所有游戏对象默认使用中心原点。若需左上角定位,请使用
    setOrigin(0, 0)
    。Text和BitmapText默认使用左上角定位。
  11. Transform.z不是depth:Transform组件的
    z
    属性用于自定义用途。渲染顺序由
    depth
    (Depth组件)或显示列表位置控制。
  12. 滤镜性能开销大:每个启用滤镜的对象会增加额外的绘制调用。可设置
    renderFilters = false
    临时禁用滤镜。内部滤镜比外部滤镜性能开销更低。

Source File Map

源文件映射

FileDescription
src/gameobjects/components/index.js
Component registry, exports all components
src/gameobjects/components/Alpha.js
Per-corner alpha mixin
src/gameobjects/components/AlphaSingle.js
Single-value alpha mixin
src/gameobjects/components/BlendMode.js
Blend mode mixin
src/gameobjects/components/Depth.js
Depth/z-order mixin
src/gameobjects/components/Flip.js
Visual flip mixin
src/gameobjects/components/GetBounds.js
Bounds calculation mixin
src/gameobjects/components/Lighting.js
v4 lighting mixin
src/gameobjects/components/Mask.js
Canvas geometry mask mixin
src/gameobjects/components/Origin.js
Origin/anchor mixin
src/gameobjects/components/ScrollFactor.js
Camera scroll factor mixin
src/gameobjects/components/Size.js
Dimensions mixin
src/gameobjects/components/Texture.js
Texture/frame assignment mixin
src/gameobjects/components/TextureCrop.js
Texture with crop support mixin
src/gameobjects/components/Tint.js
Vertex color tinting mixin
src/gameobjects/components/Transform.js
Position/scale/rotation mixin
src/gameobjects/components/Visible.js
Visibility mixin
src/gameobjects/components/PathFollower.js
Path-following mixin
src/gameobjects/components/RenderNodes.js
v4 WebGL render node mixin
src/gameobjects/components/RenderSteps.js
v4 WebGL render step mixin
src/gameobjects/components/Filters.js
v4 WebGL filter system mixin
src/gameobjects/components/FilterList.js
v4 filter list class (add effects)
src/gameobjects/components/TransformMatrix.js
2D transform matrix utility

Related skills:
sprites-and-images.md
,
custom-game-objects.md
文件描述
src/gameobjects/components/index.js
组件注册表,导出所有组件
src/gameobjects/components/Alpha.js
四角独立透明度Mixin
src/gameobjects/components/AlphaSingle.js
单一值透明度Mixin
src/gameobjects/components/BlendMode.js
混合模式Mixin
src/gameobjects/components/Depth.js
深度/z轴层级Mixin
src/gameobjects/components/Flip.js
视觉翻转Mixin
src/gameobjects/components/GetBounds.js
边界计算Mixin
src/gameobjects/components/Lighting.js
Phaser 4光照Mixin
src/gameobjects/components/Mask.js
Canvas几何遮罩Mixin
src/gameobjects/components/Origin.js
原点/锚点Mixin
src/gameobjects/components/ScrollFactor.js
相机滚动因子Mixin
src/gameobjects/components/Size.js
尺寸管理Mixin
src/gameobjects/components/Texture.js
纹理/帧分配Mixin
src/gameobjects/components/TextureCrop.js
带裁剪支持的纹理Mixin
src/gameobjects/components/Tint.js
顶点着色Mixin
src/gameobjects/components/Transform.js
位置/缩放/旋转Mixin
src/gameobjects/components/Visible.js
可见性控制Mixin
src/gameobjects/components/PathFollower.js
路径跟随Mixin
src/gameobjects/components/RenderNodes.js
Phaser 4 WebGL渲染节点Mixin
src/gameobjects/components/RenderSteps.js
Phaser 4 WebGL渲染步骤Mixin
src/gameobjects/components/Filters.js
Phaser 4 WebGL滤镜系统Mixin
src/gameobjects/components/FilterList.js
Phaser 4滤镜列表类(用于添加特效)
src/gameobjects/components/TransformMatrix.js
2D变换矩阵工具类

相关技能文档
sprites-and-images.md
,
custom-game-objects.md