mcpField
A
actions-and-utilities

actions-and-utilities

github.com/phaserjs开发40.6k774 次安装10 周前更新
代码仓库

关于 actions-and-utilities

面向 Phaser 4 游戏开发者的 Actions 与工具函数技能,介绍对游戏对象数组执行批量操作,以及数组、对象和字符串辅助函数。内容覆盖属性调整、几何布局、分布、查询和排序。

主要功能

  1. 01批量设置与递增游戏对象属性
  2. 02按几何形状放置或随机分布
  3. 03网格对齐与区域适配
  4. 04数组查询、迭代和重排
  5. 05数组、对象与字符串工具函数

适用场景

  1. 01批量排列场景中的精灵
  2. 02沿圆形或线段分布游戏对象
  3. 03调整一组对象的可见性或缩放
  4. 04筛选、排序或整理游戏数据数组

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/phaserjs/phaser --skill actions-and-utilities

安装后在 Claude Code 中输入/actions-and-utilities确认已加载。

详细介绍

Phaser 4 -- 操作与实用函数

用于对 Game Object 数组进行批量操作的 Phaser.Actions 命名空间,以及 Phaser.Utils.Array、Phaser.Utils.Objects 和 Phaser.Utils.String 辅助函数。

相关技能: ../groups-and-containers/SKILL.md, ../sprites-and-images/SKILL.md


快速开始

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

核心概念

Actions 模式

Phaser.Actions 中的每个 Action 都遵循相同的模式:

  1. 第一个参数始终是一个数组,包含 Game Object(或任何具有所需公共属性的对象,如 x、y、alpha 等)。
  2. 返回同一个数组,支持链式调用或透传。
  3. 可与 Group 配合使用,通过传入 group.getChildren()。
  4. Action 不存储状态。它们是一次性批量操作。
PropertyValueSet 与 PropertyValueInc

大多数 Set/Inc action 都委托给两个核心函数:

  • 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 = 反向)。

基于几何图形的放置

诸如 PlaceOnCircle、PlaceOnLine、RandomRectangle 等 Action 接受 Phaser 几何对象(Phaser.Geom.Circle、Phaser.Geom.Line 等),而非 Game Object 形状。如果使用 Phaser.GameObjects.Circle,请传入其 .geom 属性。


所有 Actions

属性设置器
Action签名描述
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?)通用:设置任意命名属性
属性递增器
操作签名描述
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?)增加到 angle(度)
Rotate(items, value, step?, index?, direction?)增加到 rotation(弧度)
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?)通用:递增任意命名属性
在几何图形上放置
操作签名描述
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)在三角形内随机位置
布局和对齐
操作签名描述
GridAlign(items, config)排列成网格;config:{ width, height, cellWidth, cellHeight, position, x, y }
AlignTo(items, position, offsetX?, offsetY?)使用 Phaser.Display.Align 常量将每个项目链式对齐到前一个项目旁边
FitToRegion(items, scaleMode?, region?, itemCoverage?)缩放/定位每个 GO 以填充矩形(v4.0.0+)。scaleMode:0=拉伸,-1=适合内部,1=覆盖外部
分布和插值
操作签名描述
Spread(items, property, min, max, inc?)在所有项目上从 min 到 max 线性分布属性
SmoothStep(items, property, min, max, inc?)使用 Hermite smoothstep 插值分布
SmootherStep(items, property, min, max, inc?)使用 Ken Perlin 的 smootherstep 分布
旋转和移动
操作签名描述
RotateAround(items, point, angle)围绕一个点旋转所有项目(弧度)
RotateAroundDistance(items, point, angle, distance)围绕一个点以固定距离旋转
ShiftPosition(items, x, y, direction?, output?)蛇形:将头部移动到 x/y,每个项目占据前一个项目的位置
WrapInRectangle(items, rect, padding?)环绕 x/y 以保持在矩形边界内
查询和迭代
操作签名描述
GetFirst(items, compare, index?)查找与 compare 对象中所有属性匹配的第一个项目
GetLast(items, compare, index?)查找与 compare 对象中所有属性匹配的最后一个项目
Call(items, callback, context)为每个项目调用回调
Shuffle(items)随机重新排序数组(Fisher-Yates)
ToggleVisible(items)切换每个项目上的 visible
PlayAnimation(items, key, ignoreIfPlaying?)在所有具有 anims 组件的项目上播放动画
效果 (v4.0.0+)
操作签名描述
AddEffectBloom(items, config?)为 Camera 或 GO 添加 Bloom 滤镜效果。返回 { parallelFilters, threshold, blur }[]
AddEffectShine(items, config?)添加 Shine 滤镜效果
AddMaskShape(items, config?)应用基于形状的遮罩(圆形、方形、矩形、椭圆),可选模糊

数组工具

命名空间: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)原地交换两个元素

还包括用于 2D 矩阵操作的 Phaser.Utils.Array.Matrix 子命名空间。


对象工具

命名空间:Phaser.Utils.Objects

函数签名描述
Clone(obj)对象的浅克隆
DeepCopy(obj)对象或数组的递归深拷贝
Extend(target, ...sources)jQuery 风格的 extend;将 sources 的属性复制到 target
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)如果 source 具有所有列出的键,则为 true
HasAny(source, keys)如果 source 具有任一列出的键,则为 true
HasValue(source, key)如果 source 具有该键,则为 true
IsPlainObject(obj)如果 obj 是纯 {} 对象(不是 DOM,不是 window),则为 true
Merge(obj1, obj2)将 obj2 合并到 obj1 的克隆中
MergeRight(obj1, obj2)将 obj1 合并到 obj2 的克隆中
Pick(source, keys)返回仅包含指定键的新对象
SetValue(source, key, value)设置点路径属性值

字符串工具

命名空间: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 字符串

常见模式

对 Group 使用 Actions
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);
用于交错值的 step 参数
// 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, ...
先散布再约束
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);
使用 GetValue 解析配置
// 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);
使用 NumberArray 处理资源键
// Generate frame key strings
const keys = Phaser.Utils.Array.NumberArray(1, 10, 'frame_', '.png');
// Result: ['frame_1.png', 'frame_2.png', ..., 'frame_10.png']

注意事项

  • Actions 直接操作普通数组,而不是 Group。 始终调用 group.getChildren() 来获取数组。
  • PlaceOn/Random 几何操作需要 Phaser.Geom 对象,而不是 Game Object 形状。对于 Phaser.GameObjects.Circle,传入 circle.geom。
  • 当 y 为 undefined 或 null 时,SetXY 会将 y 默认设为 x。如果你希望 y=0 而 x 为其他值,请显式传入 0。
  • Spread 在只有单个项时会将其放在中点 (min + max) / 2,而不是 min。
  • step 是与迭代索引相乘,而不是累积相加。第 0 项得到 value + 0*step,第 1 项得到 value + 1*step,依此类推。
  • 当引擎支持稳定排序时,StableSort 使用原生 Array.sort,仅在需要时回退到归并排序。
  • Shuffle(Actions 和 Utils.Array 中的都是)会原地修改数组并返回它。
  • GetValue 与 GetFastValue:当键始终位于顶层(没有点)时,使用 GetFastValue。它会跳过点路径解析,在热循环中更快。
  • AddEffectBloom / AddEffectShine / AddMaskShape 仅适用于 v4,是基于 filter 的效果。它们返回所创建效果的数组,而不是输入本身。

源文件映射

区域路径
所有 Actionssrc/actions/
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/

评论

支持 Markdown