actions-and-utilities
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePhaser 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 follows the same pattern:
Phaser.Actions- First argument is always an array of Game Objects (or any objects with the required public properties like ,
x,y, etc.).alpha - Returns the same array, enabling chaining or pass-through.
- Works with Groups by passing .
group.getChildren() - Actions do NOT store state. They are one-shot batch operations.
Phaser.Actions- 第一个参数始终是游戏对象数组(或任何具有、
x、y等所需公共属性的对象)。alpha - 返回同一个数组,支持链式调用或直接传递。
- 支持Group对象,只需传入即可。
group.getChildren() - 动作不存储状态,它们是一次性的批量操作。
PropertyValueSet and PropertyValueInc
PropertyValueSet与PropertyValueInc
Most Set/Inc actions delegate to two core functions:
- -- Sets
PropertyValueSet(items, key, value, step, index, direction).items[i][key] = value + (i * step) - -- Adds
PropertyValueInc(items, key, value, step, index, direction).items[i][key] += value + (i * step)
The parameter adds an incremental offset per item. The and parameters control iteration start point and order (1 = forward, -1 = backward).
stepindexdirection大多数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)
stepindexdirectionGeometry-Based Placement
基于几何图形的放置
Actions like , , , etc. accept Phaser geometry objects (, , etc.), NOT Game Object shapes. If using a , pass its property instead.
PlaceOnCirclePlaceOnLineRandomRectanglePhaser.Geom.CirclePhaser.Geom.LinePhaser.GameObjects.Circle.geomPlaceOnCirclePlaceOnLineRandomRectanglePhaser.Geom.CirclePhaser.Geom.LinePhaser.GameObjects.Circle.geomAll Actions
所有动作
Property Setters
属性设置器
| Action | Signature | Description |
|---|---|---|
| | Set |
| | Set |
| | Set both |
| | Set |
| | Set blend mode |
| | Set render depth |
| | Set interactive hit area |
| | Set origin point |
| | Set rotation (radians) |
| | Set both scale axes |
| | Set |
| | Set |
| | Set scroll factor |
| | Set horizontal scroll factor |
| | Set vertical scroll factor |
| | Set tint color(s) |
| | Set visibility |
| | Generic: set any named property |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 设置 |
| | 设置 |
| | 同时设置 |
| | 设置透明度 |
| | 设置混合模式 |
| | 设置渲染层级 |
| | 设置交互点击区域 |
| | 设置原点 |
| | 设置旋转角度(弧度) |
| | 同时设置缩放的两个轴 |
| | 设置 |
| | 设置 |
| | 设置滚动系数 |
| | 设置水平滚动系数 |
| | 设置垂直滚动系数 |
| | 设置着色颜色 |
| | 设置可见性 |
| | 通用方法:设置任意指定属性 |
Property Incrementers
属性增量器
| Action | Signature | Description |
|---|---|---|
| | Add to |
| | Add to |
| | Add to |
| | Add to |
| | Add to |
| | Add to |
| | Add to |
| | Add to both scale axes |
| | Add to |
| | Generic: increment any named property |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 增加 |
| | 同时增加 |
| | 增加 |
| | 增加透明度 |
| | 增加角度(度数) |
| | 增加旋转角度(弧度) |
| | 增加 |
| | 同时增加两个缩放轴的值 |
| | 增加 |
| | 通用方法:增量更新任意指定属性 |
Placement on Geometry
几何图形上的放置
| Action | Signature | Description |
|---|---|---|
| | Evenly space on circle perimeter |
| | Evenly space on ellipse perimeter |
| | Evenly space along a line |
| | Evenly space on rectangle perimeter |
| | Evenly space on triangle perimeter |
| | Random positions within a circle |
| | Random positions within an ellipse |
| | Random positions along a line |
| | Random positions within a rectangle |
| | Random positions within a triangle |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 在圆周上均匀分布 |
| | 在椭圆周上均匀分布 |
| | 在直线上均匀分布 |
| | 在矩形周上均匀分布 |
| | 在三角形周上均匀分布 |
| | 在圆内随机分布位置 |
| | 在椭圆内随机分布位置 |
| | 在直线上随机分布位置 |
| | 在矩形内随机分布位置 |
| | 在三角形内随机分布位置 |
Layout and Alignment
布局与对齐
| Action | Signature | Description |
|---|---|---|
| | Arrange in grid; config: |
| | Chain-align each item next to the previous one using |
| | Scale/position each GO to fill a rectangle (v4.0.0+). scaleMode: 0=stretch, -1=fit inside, 1=cover outside |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 排列成网格;配置项: |
| | 使用 |
| | 缩放/定位每个游戏对象以填充矩形区域(v4.0.0+)。scaleMode:0=拉伸,-1=适配内部,1=覆盖外部 |
Distribution and Interpolation
分布与插值
| Action | Signature | Description |
|---|---|---|
| | Linearly distribute a property from |
| | Distribute using Hermite smoothstep interpolation |
| | Distribute using Ken Perlin's smootherstep |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 在所有元素间线性分布属性值,从 |
| | 使用Hermite平滑插值进行分布 |
| | 使用Ken Perlin的更平滑插值进行分布 |
Rotation and Movement
旋转与移动
| Action | Signature | Description |
|---|---|---|
| | Rotate all items around a point (radians) |
| | Rotate around a point at a fixed distance |
| | Snake-like: move head to x/y, each item takes position of the previous |
| | Wrap x/y to stay within rectangle bounds |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 围绕一个点旋转所有元素(弧度) |
| | 围绕一个点固定距离旋转 |
| | 蛇形移动:将第一个元素移到x/y位置,每个后续元素占据前一个元素的位置 |
| | 循环包裹x/y坐标,使其保持在矩形边界内 |
Queries and Iteration
查询与迭代
| Action | Signature | Description |
|---|---|---|
| | Find first item matching all properties in |
| | Find last item matching all properties in |
| | Invoke callback for each item |
| | Randomly reorder the array (Fisher-Yates) |
| | Toggle |
| | Play animation on all items with an |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 查找第一个匹配 |
| | 查找最后一个匹配 |
| | 为每个元素调用回调函数 |
| | 随机重新排序数组(Fisher-Yates算法) |
| | 切换每个元素的可见性 |
| | 为所有带有 |
Effects (v4.0.0+)
特效(v4.0.0+)
| Action | Signature | Description |
|---|---|---|
| | Add Bloom filter effect to a Camera or GO. Returns |
| | Add Shine filter effect |
| | Apply a shape-based mask (circle, square, rectangle, ellipse) with optional blur |
| 动作 | 签名 | 描述 |
|---|---|---|
| | 为相机或游戏对象添加 Bloom 滤镜特效。返回 |
| | 添加 Shine 滤镜特效 |
| | 应用基于形状的遮罩(圆形、正方形、矩形、椭圆),可选模糊效果 |
Array Utilities
数组工具函数
Namespace:
Phaser.Utils.Array| Function | Signature | Description |
|---|---|---|
| | Add item(s) if not already present; optional size limit |
| | Insert item(s) at index |
| | Move item to end of array |
| | Count items where property equals value |
| | Iterate with callback; passes item + extra args |
| | Iterate a slice with callback |
| | Binary-search style closest match in sorted array |
| | Flatten nested arrays into a single array |
| | Filter items matching property/value |
| | First item matching property/value |
| | Return a random element |
| | Move item2 directly above item1 |
| | Move item2 directly below item1 |
| | Move item one position toward index 0 |
| | Move item to specific index |
| | Move item one position toward end |
| | Generate |
| | Generate range with custom step size |
| | Partial sort: kth smallest element in-place |
| | Generate array from range config |
| | Remove item(s) from array |
| | Remove item at index |
| | Remove items in range |
| | Remove and return a random element |
| | Swap one item for another |
| | Shift elements left; last wraps to front |
| | Shift elements right; first wraps to end |
| | Validate index range is within bounds |
| | Move item to index 0 |
| | Set a property on all items in range |
| | Fisher-Yates shuffle; modifies in-place |
| | Sort strings by embedded numeric values |
| | Fast single-element splice |
| | Guaranteed stable sort (merge sort fallback for engines without native stable sort) |
| | Swap two items in-place |
Also includes sub-namespace for 2D matrix operations.
Phaser.Utils.Array.Matrix命名空间:
Phaser.Utils.Array| 函数 | 签名 | 描述 |
|---|---|---|
| | 添加元素(若不存在);可选数量限制 |
| | 在指定索引处插入元素 |
| | 将元素移到数组末尾 |
| | 统计属性等于指定值的元素数量 |
| | 遍历数组并调用回调;传递元素及额外参数 |
| | 遍历数组切片并调用回调 |
| | 在已排序数组中进行二分查找式的近似匹配 |
| | 将嵌套数组扁平化为一维数组 |
| | 过滤出匹配属性/值的元素 |
| | 获取第一个匹配属性/值的元素 |
| | 返回随机元素 |
| | 将item2移到item1的正上方位置 |
| | 将item2移到item1的正下方位置 |
| | 将元素向索引0方向移动一位 |
| | 将元素移到指定索引位置 |
| | 将元素向数组末尾方向移动一位 |
| | 生成 |
| | 生成自定义步长的范围数组 |
| | 部分排序:原地找出第k小的元素 |
| | 根据范围配置生成数组 |
| | 从数组中移除元素 |
| | 移除指定索引处的元素 |
| | 移除指定范围内的元素 |
| | 移除并返回随机元素 |
| | 替换数组中的元素 |
| | 向左移位;最后一个元素移到开头 |
| | 向右移位;第一个元素移到末尾 |
| | 验证索引范围是否在数组边界内 |
| | 将元素移到数组开头(索引0) |
| | 设置指定范围内所有元素的属性值 |
| | Fisher-Yates洗牌;原地修改数组 |
| | 根据字符串中嵌入的数值进行排序 |
| | 快速移除单个元素 |
| | 稳定排序(若引擎不支持原生稳定排序,则回退到归并排序) |
| | 原地交换两个元素的位置 |
还包含子命名空间,用于二维矩阵操作。
Phaser.Utils.Array.MatrixObject Utilities
对象工具函数
Namespace:
Phaser.Utils.Objects| Function | Signature | Description |
|---|---|---|
| | Shallow clone of object |
| | Recursive deep copy of object or array |
| | jQuery-style extend; copies properties from sources to target |
| | Like |
| | Top-level-only property lookup; no dot-path support. Faster than |
| | Get value clamped between min and max |
| | Dot-path property lookup (e.g. |
| | True if source has ALL listed keys |
| | True if source has ANY listed key |
| | True if source has the key |
| | True if obj is a plain |
| | Merge obj2 into a clone of obj1 |
| | Merge obj1 into a clone of obj2 |
| | Return new object with only the specified keys |
| | Set a dot-path property value |
命名空间:
Phaser.Utils.Objects| 函数 | 签名 | 描述 |
|---|---|---|
| | 对象的浅克隆 |
| | 对象或数组的递归深拷贝 |
| | jQuery风格的扩展;将源对象的属性复制到目标对象 |
| | 类似 |
| | 仅顶层属性查找;不支持点路径。比 |
| | 获取限制在min和max之间的值 |
| | 点路径属性查找(例如 |
| | 如果源对象包含所有列出的键则返回true |
| | 如果源对象包含任意列出的键则返回true |
| | 如果源对象包含指定键则返回true |
| | 如果obj是普通 |
| | 将obj2合并到obj1的克隆中 |
| | 将obj1合并到obj2的克隆中 |
| | 返回仅包含指定键的新对象 |
| | 设置点路径属性的值 |
String Utilities
字符串工具函数
Namespace:
Phaser.Utils.String| Function | Signature | Description |
|---|---|---|
| | Replace |
| | Pad string to length. dir: 1=left, 2=right, default=both |
| | Remove character at index |
| | Reverse the string |
| | Capitalize first character |
| | Generate RFC4122 v4 UUID string |
命名空间:
Phaser.Utils.String| 函数 | 签名 | 描述 |
|---|---|---|
| | 将 |
| | 将字符串填充到指定长度。dir:1=左填充,2=右填充,默认=两端填充 |
| | 删除指定索引处的字符 |
| | 反转字符串 |
| | 将首字母大写 |
| | 生成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 to get the array.
group.getChildren() - PlaceOn/Random geometry actions need objects, not Game Object shapes. For a
Phaser.Geom, passPhaser.GameObjects.Circle.circle.geom - defaults
SetXYtoyifxisyorundefined. Passnullexplicitly if you want y=0 and x=something else.0 - with a single item places it at the midpoint
Spread, not at(min + max) / 2.min - is multiplied by iteration index, not added cumulatively. Item 0 gets
step, item 1 getsvalue + 0*step, etc.value + 1*step - uses native
StableSortwhen the engine supports stable sorting, falling back to merge sort only when needed.Array.sort - (both Actions and Utils.Array) modifies the array in-place and returns it.
Shuffle - vs
GetValue: UseGetFastValuewhen the key is always top-level (no dots). It skips dot-path parsing and is faster in hot loops.GetFastValue - /
AddEffectBloom/AddEffectShineare v4-only filter-based effects. They return arrays of created effects instead of the input.AddMaskShape
- 动作仅操作普通数组,不直接操作Group对象。必须调用获取数组。
group.getChildren() - PlaceOn/Random类几何动作需要对象,而非游戏对象形状。对于
Phaser.Geom,请传入Phaser.GameObjects.Circle。circle.geom - 在
SetXY未定义或为y时默认等于null。如果需要y=0而x为其他值,请显式传入0。x - 单个元素使用时,会将属性值设置为中点
Spread,而非(min + max) / 2。min - 是与迭代索引相乘,而非累积相加。第0个元素得到
step,第1个元素得到value + 0*step,以此类推。value + 1*step - 在引擎支持原生稳定排序时使用
StableSort,仅在必要时回退到归并排序。Array.sort - (动作和Utils.Array中的版本)都会原地修改数组并返回该数组。
Shuffle - vs
GetValue:当键始终是顶层(无点)时使用GetFastValue。它跳过点路径解析,在热循环中性能更好。GetFastValue - /
AddEffectBloom/AddEffectShine仅在v4版本可用,是基于滤镜的特效。它们返回创建的特效数组,而非输入对象。AddMaskShape
Source File Map
源文件映射
| Area | Path |
|---|---|
| All Actions | |
| Actions index | |
| Core set/inc helpers | |
| GridAlign config typedef | |
| Array utilities | |
| Array matrix utils | |
| Object utilities | |
| String utilities | |
| 模块 | 路径 |
|---|---|
| 所有动作 | |
| 动作入口 | |
| 核心set/inc辅助函数 | |
| GridAlign配置类型定义 | |
| 数组工具函数 | |
| 数组矩阵工具函数 | |
| 对象工具函数 | |
| 字符串工具函数 | |