actions-and-utilities

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Phaser 4 -- Actions & Utility Functions

Phaser 4 -- 动作与工具函数

Phaser.Actions namespace for batch operations on Game Object arrays, plus Phaser.Utils.Array, Phaser.Utils.Objects, and Phaser.Utils.String helper functions.
Related skills: ../groups-and-containers/SKILL.md, ../sprites-and-images/SKILL.md

Phaser.Actions命名空间用于对游戏对象数组执行批量操作,同时包含Phaser.Utils.Array、Phaser.Utils.Objects和Phaser.Utils.String辅助函数。
相关技能: ../groups-and-containers/SKILL.md, ../sprites-and-images/SKILL.md

Quick Start

快速入门

js
// Create 20 sprites and batch-position them in a grid
const sprites = [];
for (let i = 0; i < 20; i++) {
    sprites.push(this.add.sprite(0, 0, 'gem'));
}

// Arrange into a 5x4 grid
Phaser.Actions.GridAlign(sprites, {
    width: 5,
    height: 4,
    cellWidth: 64,
    cellHeight: 64,
    x: 100,
    y: 100
});

// Fade alpha from 0 to 1 across all sprites
Phaser.Actions.Spread(sprites, 'alpha', 0, 1);

// Offset each sprite's x by 10, with a step of 2 per item
Phaser.Actions.IncX(sprites, 10, 2);

// Works with Groups too
const group = this.add.group({ key: 'star', repeat: 11 });
Phaser.Actions.PlaceOnCircle(group.getChildren(), new Phaser.Geom.Circle(400, 300, 200));

js
// 创建20个精灵并将它们批量排列成网格
const sprites = [];
for (let i = 0; i < 20; i++) {
    sprites.push(this.add.sprite(0, 0, 'gem'));
}

// 排列成5x4的网格
Phaser.Actions.GridAlign(sprites, {
    width: 5,
    height: 4,
    cellWidth: 64,
    cellHeight: 64,
    x: 100,
    y: 100
});

// 将所有精灵的透明度从0渐变到1
Phaser.Actions.Spread(sprites, 'alpha', 0, 1);

// 每个精灵的x坐标偏移10,且每个后续精灵额外增加2
Phaser.Actions.IncX(sprites, 10, 2);

// 同样适用于Group对象
const group = this.add.group({ key: 'star', repeat: 11 });
Phaser.Actions.PlaceOnCircle(group.getChildren(), new Phaser.Geom.Circle(400, 300, 200));

Core Concepts

核心概念

The Actions Pattern

动作模式

Every Action in
Phaser.Actions
follows the same pattern:
  1. First argument is always an array of Game Objects (or any objects with the required public properties like
    x
    ,
    y
    ,
    alpha
    , etc.).
  2. Returns the same array, enabling chaining or pass-through.
  3. Works with Groups by passing
    group.getChildren()
    .
  4. Actions do NOT store state. They are one-shot batch operations.
Phaser.Actions
中的每个动作都遵循相同的模式:
  1. 第一个参数始终是游戏对象数组(或任何具有
    x
    y
    alpha
    等所需公共属性的对象)。
  2. 返回同一个数组,支持链式调用或直接传递。
  3. 支持Group对象,只需传入
    group.getChildren()
    即可。
  4. 动作不存储状态,它们是一次性的批量操作。

PropertyValueSet and PropertyValueInc

PropertyValueSet与PropertyValueInc

Most Set/Inc actions delegate to two core functions:
  • PropertyValueSet(items, key, value, step, index, direction)
    -- Sets
    items[i][key] = value + (i * step)
    .
  • PropertyValueInc(items, key, value, step, index, direction)
    -- Adds
    items[i][key] += value + (i * step)
    .
The
step
parameter adds an incremental offset per item. The
index
and
direction
parameters control iteration start point and order (1 = forward, -1 = backward).
大多数Set/Inc动作都基于两个核心函数实现:
  • PropertyValueSet(items, key, value, step, index, direction)
    -- 设置
    items[i][key] = value + (i * step)
  • PropertyValueInc(items, key, value, step, index, direction)
    -- 执行
    items[i][key] += value + (i * step)
step
参数为每个元素添加递增偏移量。
index
direction
参数控制迭代的起始点和顺序(1=正向,-1=反向)。

Geometry-Based Placement

基于几何图形的放置

Actions like
PlaceOnCircle
,
PlaceOnLine
,
RandomRectangle
, etc. accept Phaser geometry objects (
Phaser.Geom.Circle
,
Phaser.Geom.Line
, etc.), NOT Game Object shapes. If using a
Phaser.GameObjects.Circle
, pass its
.geom
property instead.

PlaceOnCircle
PlaceOnLine
RandomRectangle
等动作接受Phaser几何对象(
Phaser.Geom.Circle
Phaser.Geom.Line
等),而非游戏对象形状。如果使用
Phaser.GameObjects.Circle
,请传入其
.geom
属性。

All Actions

所有动作

Property Setters

属性设置器

ActionSignatureDescription
SetX
(items, value, step?, index?, direction?)
Set
x
property
SetY
(items, value, step?, index?, direction?)
Set
y
property
SetXY
(items, x, y?, stepX?, stepY?, index?, direction?)
Set both
x
and
y
;
y
defaults to
x
SetAlpha
(items, value, step?, index?, direction?)
Set
alpha
SetBlendMode
(items, value, index?, direction?)
Set blend mode
SetDepth
(items, value, step?, index?, direction?)
Set render depth
SetHitArea
(items, hitArea?, callback?)
Set interactive hit area
SetOrigin
(items, originX, originY?, stepX?, stepY?, index?, direction?)
Set origin point
SetRotation
(items, value, step?, index?, direction?)
Set rotation (radians)
SetScale
(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)
Set both scale axes
SetScaleX
(items, value, step?, index?, direction?)
Set
scaleX
SetScaleY
(items, value, step?, index?, direction?)
Set
scaleY
SetScrollFactor
(items, x, y?, stepX?, stepY?, index?, direction?)
Set scroll factor
SetScrollFactorX
(items, value, step?, index?, direction?)
Set horizontal scroll factor
SetScrollFactorY
(items, value, step?, index?, direction?)
Set vertical scroll factor
SetTint
(items, topLeft, topRight?, bottomLeft?, bottomRight?)
Set tint color(s)
SetVisible
(items, value, index?, direction?)
Set visibility
PropertyValueSet
(items, key, value, step?, index?, direction?)
Generic: set any named property
动作签名描述
SetX
(items, value, step?, index?, direction?)
设置
x
属性
SetY
(items, value, step?, index?, direction?)
设置
y
属性
SetXY
(items, x, y?, stepX?, stepY?, index?, direction?)
同时设置
x
y
;若未传入
y
则默认等于
x
SetAlpha
(items, value, step?, index?, direction?)
设置透明度
alpha
SetBlendMode
(items, value, index?, direction?)
设置混合模式
SetDepth
(items, value, step?, index?, direction?)
设置渲染层级
SetHitArea
(items, hitArea?, callback?)
设置交互点击区域
SetOrigin
(items, originX, originY?, stepX?, stepY?, index?, direction?)
设置原点
SetRotation
(items, value, step?, index?, direction?)
设置旋转角度(弧度)
SetScale
(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)
同时设置缩放的两个轴
SetScaleX
(items, value, step?, index?, direction?)
设置
scaleX
SetScaleY
(items, value, step?, index?, direction?)
设置
scaleY
SetScrollFactor
(items, x, y?, stepX?, stepY?, index?, direction?)
设置滚动系数
SetScrollFactorX
(items, value, step?, index?, direction?)
设置水平滚动系数
SetScrollFactorY
(items, value, step?, index?, direction?)
设置垂直滚动系数
SetTint
(items, topLeft, topRight?, bottomLeft?, bottomRight?)
设置着色颜色
SetVisible
(items, value, index?, direction?)
设置可见性
PropertyValueSet
(items, key, value, step?, index?, direction?)
通用方法:设置任意指定属性

Property Incrementers

属性增量器

ActionSignatureDescription
IncX
(items, value, step?, index?, direction?)
Add to
x
IncXY
(items, x, y?, stepX?, stepY?, index?, direction?)
Add to
x
and
y
IncY
(items, value, step?, index?, direction?)
Add to
y
IncAlpha
(items, value, step?, index?, direction?)
Add to
alpha
Angle
(items, value, step?, index?, direction?)
Add to
angle
(degrees)
Rotate
(items, value, step?, index?, direction?)
Add to
rotation
(radians)
ScaleX
(items, value, step?, index?, direction?)
Add to
scaleX
ScaleXY
(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)
Add to both scale axes
ScaleY
(items, value, step?, index?, direction?)
Add to
scaleY
PropertyValueInc
(items, key, value, step?, index?, direction?)
Generic: increment any named property
动作签名描述
IncX
(items, value, step?, index?, direction?)
增加
x
属性值
IncXY
(items, x, y?, stepX?, stepY?, index?, direction?)
同时增加
x
y
属性值
IncY
(items, value, step?, index?, direction?)
增加
y
属性值
IncAlpha
(items, value, step?, index?, direction?)
增加透明度
alpha
Angle
(items, value, step?, index?, direction?)
增加角度(度数)
Rotate
(items, value, step?, index?, direction?)
增加旋转角度(弧度)
ScaleX
(items, value, step?, index?, direction?)
增加
scaleX
ScaleXY
(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)
同时增加两个缩放轴的值
ScaleY
(items, value, step?, index?, direction?)
增加
scaleY
PropertyValueInc
(items, key, value, step?, index?, direction?)
通用方法:增量更新任意指定属性

Placement on Geometry

几何图形上的放置

ActionSignatureDescription
PlaceOnCircle
(items, circle, startAngle?, endAngle?)
Evenly space on circle perimeter
PlaceOnEllipse
(items, ellipse, startAngle?, endAngle?)
Evenly space on ellipse perimeter
PlaceOnLine
(items, line)
Evenly space along a line
PlaceOnRectangle
(items, rect, shift?)
Evenly space on rectangle perimeter
PlaceOnTriangle
(items, triangle, stepRate?)
Evenly space on triangle perimeter
RandomCircle
(items, circle)
Random positions within a circle
RandomEllipse
(items, ellipse)
Random positions within an ellipse
RandomLine
(items, line)
Random positions along a line
RandomRectangle
(items, rect)
Random positions within a rectangle
RandomTriangle
(items, triangle)
Random positions within a triangle
动作签名描述
PlaceOnCircle
(items, circle, startAngle?, endAngle?)
在圆周上均匀分布
PlaceOnEllipse
(items, ellipse, startAngle?, endAngle?)
在椭圆周上均匀分布
PlaceOnLine
(items, line)
在直线上均匀分布
PlaceOnRectangle
(items, rect, shift?)
在矩形周上均匀分布
PlaceOnTriangle
(items, triangle, stepRate?)
在三角形周上均匀分布
RandomCircle
(items, circle)
在圆内随机分布位置
RandomEllipse
(items, ellipse)
在椭圆内随机分布位置
RandomLine
(items, line)
在直线上随机分布位置
RandomRectangle
(items, rect)
在矩形内随机分布位置
RandomTriangle
(items, triangle)
在三角形内随机分布位置

Layout and Alignment

布局与对齐

ActionSignatureDescription
GridAlign
(items, config)
Arrange in grid; config:
{ width, height, cellWidth, cellHeight, position, x, y }
AlignTo
(items, position, offsetX?, offsetY?)
Chain-align each item next to the previous one using
Phaser.Display.Align
constants
FitToRegion
(items, scaleMode?, region?, itemCoverage?)
Scale/position each GO to fill a rectangle (v4.0.0+). scaleMode: 0=stretch, -1=fit inside, 1=cover outside
动作签名描述
GridAlign
(items, config)
排列成网格;配置项:
{ width, height, cellWidth, cellHeight, position, x, y }
AlignTo
(items, position, offsetX?, offsetY?)
使用
Phaser.Display.Align
常量,将每个元素依次对齐到前一个元素旁边
FitToRegion
(items, scaleMode?, region?, itemCoverage?)
缩放/定位每个游戏对象以填充矩形区域(v4.0.0+)。scaleMode:0=拉伸,-1=适配内部,1=覆盖外部

Distribution and Interpolation

分布与插值

ActionSignatureDescription
Spread
(items, property, min, max, inc?)
Linearly distribute a property from
min
to
max
across all items
SmoothStep
(items, property, min, max, inc?)
Distribute using Hermite smoothstep interpolation
SmootherStep
(items, property, min, max, inc?)
Distribute using Ken Perlin's smootherstep
动作签名描述
Spread
(items, property, min, max, inc?)
在所有元素间线性分布属性值,从
min
max
SmoothStep
(items, property, min, max, inc?)
使用Hermite平滑插值进行分布
SmootherStep
(items, property, min, max, inc?)
使用Ken Perlin的更平滑插值进行分布

Rotation and Movement

旋转与移动

ActionSignatureDescription
RotateAround
(items, point, angle)
Rotate all items around a point (radians)
RotateAroundDistance
(items, point, angle, distance)
Rotate around a point at a fixed distance
ShiftPosition
(items, x, y, direction?, output?)
Snake-like: move head to x/y, each item takes position of the previous
WrapInRectangle
(items, rect, padding?)
Wrap x/y to stay within rectangle bounds
动作签名描述
RotateAround
(items, point, angle)
围绕一个点旋转所有元素(弧度)
RotateAroundDistance
(items, point, angle, distance)
围绕一个点固定距离旋转
ShiftPosition
(items, x, y, direction?, output?)
蛇形移动:将第一个元素移到x/y位置,每个后续元素占据前一个元素的位置
WrapInRectangle
(items, rect, padding?)
循环包裹x/y坐标,使其保持在矩形边界内

Queries and Iteration

查询与迭代

ActionSignatureDescription
GetFirst
(items, compare, index?)
Find first item matching all properties in
compare
object
GetLast
(items, compare, index?)
Find last item matching all properties in
compare
object
Call
(items, callback, context)
Invoke callback for each item
Shuffle
(items)
Randomly reorder the array (Fisher-Yates)
ToggleVisible
(items)
Toggle
visible
on each item
PlayAnimation
(items, key, ignoreIfPlaying?)
Play animation on all items with an
anims
component
动作签名描述
GetFirst
(items, compare, index?)
查找第一个匹配
compare
对象中所有属性的元素
GetLast
(items, compare, index?)
查找最后一个匹配
compare
对象中所有属性的元素
Call
(items, callback, context)
为每个元素调用回调函数
Shuffle
(items)
随机重新排序数组(Fisher-Yates算法)
ToggleVisible
(items)
切换每个元素的可见性
PlayAnimation
(items, key, ignoreIfPlaying?)
为所有带有
anims
组件的元素播放动画

Effects (v4.0.0+)

特效(v4.0.0+)

ActionSignatureDescription
AddEffectBloom
(items, config?)
Add Bloom filter effect to a Camera or GO. Returns
{ parallelFilters, threshold, blur }[]
AddEffectShine
(items, config?)
Add Shine filter effect
AddMaskShape
(items, config?)
Apply a shape-based mask (circle, square, rectangle, ellipse) with optional blur

动作签名描述
AddEffectBloom
(items, config?)
为相机或游戏对象添加 Bloom 滤镜特效。返回
{ parallelFilters, threshold, blur }[]
AddEffectShine
(items, config?)
添加 Shine 滤镜特效
AddMaskShape
(items, config?)
应用基于形状的遮罩(圆形、正方形、矩形、椭圆),可选模糊效果

Array Utilities

数组工具函数

Namespace:
Phaser.Utils.Array
FunctionSignatureDescription
Add
(array, item, limit?, callback?, context?)
Add item(s) if not already present; optional size limit
AddAt
(array, item, index?, limit?, callback?, context?)
Insert item(s) at index
BringToTop
(array, item)
Move item to end of array
CountAllMatching
(array, property, value, startIndex?, endIndex?)
Count items where property equals value
Each
(array, callback, context, ...args)
Iterate with callback; passes item + extra args
EachInRange
(array, callback, context, startIndex, endIndex, ...args)
Iterate a slice with callback
FindClosestInSorted
(value, array, key?)
Binary-search style closest match in sorted array
Flatten
(array, output?)
Flatten nested arrays into a single array
GetAll
(array, property?, value?, startIndex?, endIndex?)
Filter items matching property/value
GetFirst
(array, property?, value?, startIndex?, endIndex?)
First item matching property/value
GetRandom
(array, startIndex?, length?)
Return a random element
MoveAbove
(array, item1, item2)
Move item2 directly above item1
MoveBelow
(array, item1, item2)
Move item2 directly below item1
MoveDown
(array, item)
Move item one position toward index 0
MoveTo
(array, item, index)
Move item to specific index
MoveUp
(array, item)
Move item one position toward end
NumberArray
(start, end, prefix?, suffix?)
Generate
[start..end]
range; optional string prefix/suffix
NumberArrayStep
(start?, end?, step?)
Generate range with custom step size
QuickSelect
(array, k, left?, right?, compare?)
Partial sort: kth smallest element in-place
Range
(a, b, options?)
Generate array from range config
Remove
(array, item, callback?, context?)
Remove item(s) from array
RemoveAt
(array, index, callback?, context?)
Remove item at index
RemoveBetween
(array, startIndex, endIndex, callback?, context?)
Remove items in range
RemoveRandomElement
(array, startIndex?, length?)
Remove and return a random element
Replace
(array, oldItem, newItem)
Swap one item for another
RotateLeft
(array, total?)
Shift elements left; last wraps to front
RotateRight
(array, total?)
Shift elements right; first wraps to end
SafeRange
(array, startIndex, endIndex, throwError?)
Validate index range is within bounds
SendToBack
(array, item)
Move item to index 0
SetAll
(array, property, value, startIndex?, endIndex?)
Set a property on all items in range
Shuffle
(array)
Fisher-Yates shuffle; modifies in-place
SortByDigits
(array)
Sort strings by embedded numeric values
SpliceOne
(array, index)
Fast single-element splice
StableSort
(array, compare?)
Guaranteed stable sort (merge sort fallback for engines without native stable sort)
Swap
(array, item1, item2)
Swap two items in-place
Also includes
Phaser.Utils.Array.Matrix
sub-namespace for 2D matrix operations.

命名空间:
Phaser.Utils.Array
函数签名描述
Add
(array, item, limit?, callback?, context?)
添加元素(若不存在);可选数量限制
AddAt
(array, item, index?, limit?, callback?, context?)
在指定索引处插入元素
BringToTop
(array, item)
将元素移到数组末尾
CountAllMatching
(array, property, value, startIndex?, endIndex?)
统计属性等于指定值的元素数量
Each
(array, callback, context, ...args)
遍历数组并调用回调;传递元素及额外参数
EachInRange
(array, callback, context, startIndex, endIndex, ...args)
遍历数组切片并调用回调
FindClosestInSorted
(value, array, key?)
在已排序数组中进行二分查找式的近似匹配
Flatten
(array, output?)
将嵌套数组扁平化为一维数组
GetAll
(array, property?, value?, startIndex?, endIndex?)
过滤出匹配属性/值的元素
GetFirst
(array, property?, value?, startIndex?, endIndex?)
获取第一个匹配属性/值的元素
GetRandom
(array, startIndex?, length?)
返回随机元素
MoveAbove
(array, item1, item2)
将item2移到item1的正上方位置
MoveBelow
(array, item1, item2)
将item2移到item1的正下方位置
MoveDown
(array, item)
将元素向索引0方向移动一位
MoveTo
(array, item, index)
将元素移到指定索引位置
MoveUp
(array, item)
将元素向数组末尾方向移动一位
NumberArray
(start, end, prefix?, suffix?)
生成
[start..end]
范围的数组;可选字符串前缀/后缀
NumberArrayStep
(start?, end?, step?)
生成自定义步长的范围数组
QuickSelect
(array, k, left?, right?, compare?)
部分排序:原地找出第k小的元素
Range
(a, b, options?)
根据范围配置生成数组
Remove
(array, item, callback?, context?)
从数组中移除元素
RemoveAt
(array, index, callback?, context?)
移除指定索引处的元素
RemoveBetween
(array, startIndex, endIndex, callback?, context?)
移除指定范围内的元素
RemoveRandomElement
(array, startIndex?, length?)
移除并返回随机元素
Replace
(array, oldItem, newItem)
替换数组中的元素
RotateLeft
(array, total?)
向左移位;最后一个元素移到开头
RotateRight
(array, total?)
向右移位;第一个元素移到末尾
SafeRange
(array, startIndex, endIndex, throwError?)
验证索引范围是否在数组边界内
SendToBack
(array, item)
将元素移到数组开头(索引0)
SetAll
(array, property, value, startIndex?, endIndex?)
设置指定范围内所有元素的属性值
Shuffle
(array)
Fisher-Yates洗牌;原地修改数组
SortByDigits
(array)
根据字符串中嵌入的数值进行排序
SpliceOne
(array, index)
快速移除单个元素
StableSort
(array, compare?)
稳定排序(若引擎不支持原生稳定排序,则回退到归并排序)
Swap
(array, item1, item2)
原地交换两个元素的位置
还包含
Phaser.Utils.Array.Matrix
子命名空间,用于二维矩阵操作。

Object Utilities

对象工具函数

Namespace:
Phaser.Utils.Objects
FunctionSignatureDescription
Clone
(obj)
Shallow clone of object
DeepCopy
(obj)
Recursive deep copy of object or array
Extend
(target, ...sources)
jQuery-style extend; copies properties from sources to target
GetAdvancedValue
(source, key, defaultValue)
Like
GetValue
but resolves random/callback config values
GetFastValue
(source, key, defaultValue?)
Top-level-only property lookup; no dot-path support. Faster than
GetValue
GetMinMaxValue
(source, key, min, max, defaultValue)
Get value clamped between min and max
GetValue
(source, key, defaultValue, altSource?)
Dot-path property lookup (e.g.
'render.screen.width'
). Falls back to altSource then defaultValue
HasAll
(source, keys)
True if source has ALL listed keys
HasAny
(source, keys)
True if source has ANY listed key
HasValue
(source, key)
True if source has the key
IsPlainObject
(obj)
True if obj is a plain
{}
object (not DOM, not window)
Merge
(obj1, obj2)
Merge obj2 into a clone of obj1
MergeRight
(obj1, obj2)
Merge obj1 into a clone of obj2
Pick
(source, keys)
Return new object with only the specified keys
SetValue
(source, key, value)
Set a dot-path property value

命名空间:
Phaser.Utils.Objects
函数签名描述
Clone
(obj)
对象的浅克隆
DeepCopy
(obj)
对象或数组的递归深拷贝
Extend
(target, ...sources)
jQuery风格的扩展;将源对象的属性复制到目标对象
GetAdvancedValue
(source, key, defaultValue)
类似
GetValue
,但支持解析随机/回调配置值
GetFastValue
(source, key, defaultValue?)
仅顶层属性查找;不支持点路径。比
GetValue
更快
GetMinMaxValue
(source, key, min, max, defaultValue)
获取限制在min和max之间的值
GetValue
(source, key, defaultValue, altSource?)
点路径属性查找(例如
'render.screen.width'
)。若找不到则回退到altSource,再回退到defaultValue
HasAll
(source, keys)
如果源对象包含所有列出的键则返回true
HasAny
(source, keys)
如果源对象包含任意列出的键则返回true
HasValue
(source, key)
如果源对象包含指定键则返回true
IsPlainObject
(obj)
如果obj是普通
{}
对象(不是DOM对象或window)则返回true
Merge
(obj1, obj2)
将obj2合并到obj1的克隆中
MergeRight
(obj1, obj2)
将obj1合并到obj2的克隆中
Pick
(source, keys)
返回仅包含指定键的新对象
SetValue
(source, key, value)
设置点路径属性的值

String Utilities

字符串工具函数

Namespace:
Phaser.Utils.String
FunctionSignatureDescription
Format
(string, values)
Replace
%1
,
%2
, etc. markers with array values
Pad
(str, len?, pad?, dir?)
Pad string to length. dir: 1=left, 2=right, default=both
RemoveAt
(string, index)
Remove character at index
Reverse
(string)
Reverse the string
UppercaseFirst
(string)
Capitalize first character
UUID
()
Generate RFC4122 v4 UUID string

命名空间:
Phaser.Utils.String
函数签名描述
Format
(string, values)
%1
%2
等标记替换为数组中的值
Pad
(str, len?, pad?, dir?)
将字符串填充到指定长度。dir:1=左填充,2=右填充,默认=两端填充
RemoveAt
(string, index)
删除指定索引处的字符
Reverse
(string)
反转字符串
UppercaseFirst
(string)
将首字母大写
UUID
()
生成RFC4122 v4 UUID字符串

Common Patterns

常见模式

Using Actions with Groups

结合Group使用动作

js
const enemies = this.add.group({ key: 'enemy', repeat: 9 });

// Position all children in a grid
Phaser.Actions.GridAlign(enemies.getChildren(), {
    width: 5, height: 2,
    cellWidth: 80, cellHeight: 80,
    x: 100, y: 50
});

// Fan out alpha across all enemies
Phaser.Actions.Spread(enemies.getChildren(), 'alpha', 0.3, 1);
js
const enemies = this.add.group({ key: 'enemy', repeat: 9 });

// 将所有子元素排列成网格
Phaser.Actions.GridAlign(enemies.getChildren(), {
    width: 5, height: 2,
    cellWidth: 80, cellHeight: 80,
    x: 100, y: 50
});

// 让所有敌人的透明度呈扇形分布
Phaser.Actions.Spread(enemies.getChildren(), 'alpha', 0.3, 1);

Step Parameter for Staggered Values

使用Step参数实现交错值

js
// Place sprites starting at x=100, each one 50px further right
Phaser.Actions.SetX(sprites, 100, 50);
// Result: items[0].x=100, items[1].x=150, items[2].x=200, ...

// Increment rotation with increasing step
Phaser.Actions.Rotate(sprites, 0.1, 0.05);
// Result: items[0].rotation += 0.1, items[1].rotation += 0.15, items[2].rotation += 0.2, ...
js
// 将精灵放置在x=100的位置,每个后续精灵向右偏移50px
Phaser.Actions.SetX(sprites, 100, 50);
// 结果:items[0].x=100, items[1].x=150, items[2].x=200, ...

// 递增旋转角度,且步长逐渐增加
Phaser.Actions.Rotate(sprites, 0.1, 0.05);
// 结果:items[0].rotation += 0.1, items[1].rotation += 0.15, items[2].rotation += 0.2, ...

Scatter Then Constrain

先分散再约束

js
const bounds = new Phaser.Geom.Rectangle(0, 0, 800, 600);
// Random scatter
Phaser.Actions.RandomRectangle(sprites, bounds);
// Keep wrapped in bounds during update
Phaser.Actions.WrapInRectangle(sprites, bounds);
js
const bounds = new Phaser.Geom.Rectangle(0, 0, 800, 600);
// 随机分散
Phaser.Actions.RandomRectangle(sprites, bounds);
// 在更新时保持在边界内循环
Phaser.Actions.WrapInRectangle(sprites, bounds);

GetValue for Config Parsing

使用GetValue解析配置

js
// Deep property access with fallback
const width = Phaser.Utils.Objects.GetValue(config, 'render.screen.width', 800);

// Fast top-level lookup (no dot-path, better performance)
const speed = Phaser.Utils.Objects.GetFastValue(config, 'speed', 100);
js
// 深度属性访问,带回退值
const width = Phaser.Utils.Objects.GetValue(config, 'render.screen.width', 800);

// 快速顶层查找(不支持点路径,性能更好)
const speed = Phaser.Utils.Objects.GetFastValue(config, 'speed', 100);

NumberArray for Asset Keys

使用NumberArray生成资源键名

js
// Generate frame key strings
const keys = Phaser.Utils.Array.NumberArray(1, 10, 'frame_', '.png');
// Result: ['frame_1.png', 'frame_2.png', ..., 'frame_10.png']

js
// 生成帧键字符串
const keys = Phaser.Utils.Array.NumberArray(1, 10, 'frame_', '.png');
// 结果:['frame_1.png', 'frame_2.png', ..., 'frame_10.png']

Gotchas

注意事项

  • Actions operate on plain arrays, not Groups directly. Always call
    group.getChildren()
    to get the array.
  • PlaceOn/Random geometry actions need
    Phaser.Geom
    objects
    , not Game Object shapes. For a
    Phaser.GameObjects.Circle
    , pass
    circle.geom
    .
  • SetXY
    defaults
    y
    to
    x
    if
    y
    is
    undefined
    or
    null
    . Pass
    0
    explicitly if you want y=0 and x=something else.
  • Spread
    with a single item
    places it at the midpoint
    (min + max) / 2
    , not at
    min
    .
  • step
    is multiplied by iteration index
    , not added cumulatively. Item 0 gets
    value + 0*step
    , item 1 gets
    value + 1*step
    , etc.
  • StableSort
    uses native
    Array.sort
    when the engine supports stable sorting
    , falling back to merge sort only when needed.
  • Shuffle
    (both Actions and Utils.Array) modifies the array in-place
    and returns it.
  • GetValue
    vs
    GetFastValue
    : Use
    GetFastValue
    when the key is always top-level (no dots). It skips dot-path parsing and is faster in hot loops.
  • AddEffectBloom
    /
    AddEffectShine
    /
    AddMaskShape
    are v4-only
    filter-based effects. They return arrays of created effects instead of the input.

  • 动作仅操作普通数组,不直接操作Group对象。必须调用
    group.getChildren()
    获取数组。
  • PlaceOn/Random类几何动作需要
    Phaser.Geom
    对象
    ,而非游戏对象形状。对于
    Phaser.GameObjects.Circle
    ,请传入
    circle.geom
  • SetXY
    y
    未定义或为
    null
    时默认等于
    x
    。如果需要y=0而x为其他值,请显式传入0。
  • 单个元素使用
    Spread
    ,会将属性值设置为中点
    (min + max) / 2
    ,而非
    min
  • step
    是与迭代索引相乘
    ,而非累积相加。第0个元素得到
    value + 0*step
    ,第1个元素得到
    value + 1*step
    ,以此类推。
  • StableSort
    在引擎支持原生稳定排序时使用
    Array.sort
    ,仅在必要时回退到归并排序。
  • Shuffle
    (动作和Utils.Array中的版本)都会原地修改数组
    并返回该数组。
  • GetValue
    vs
    GetFastValue
    :当键始终是顶层(无点)时使用
    GetFastValue
    。它跳过点路径解析,在热循环中性能更好。
  • AddEffectBloom
    /
    AddEffectShine
    /
    AddMaskShape
    仅在v4版本可用
    ,是基于滤镜的特效。它们返回创建的特效数组,而非输入对象。

Source File Map

源文件映射

AreaPath
All Actions
src/actions/
Actions index
src/actions/index.js
Core set/inc helpers
src/actions/PropertyValueSet.js
,
src/actions/PropertyValueInc.js
GridAlign config typedef
src/actions/typedefs/
Array utilities
src/utils/array/
Array matrix utils
src/utils/array/matrix/
Object utilities
src/utils/object/
String utilities
src/utils/string/
模块路径
所有动作
src/actions/
动作入口
src/actions/index.js
核心set/inc辅助函数
src/actions/PropertyValueSet.js
,
src/actions/PropertyValueInc.js
GridAlign配置类型定义
src/actions/typedefs/
数组工具函数
src/utils/array/
数组矩阵工具函数
src/utils/array/matrix/
对象工具函数
src/utils/object/
字符串工具函数
src/utils/string/