1---2name: actions-and-utilities3description: "Use this skill when working with Phaser 4 utility functions, actions, alignment, grid layout, or batch operations on game objects. Triggers on: align, grid layout, actions, set operations on groups of game objects."4metadata:5 source: https://skillmd.com/skills/phaserjs/actions-and-utilities6---78# Phaser 4 -- Actions & Utility Functions910> Phaser.Actions namespace for batch operations on Game Object arrays, plus Phaser.Utils.Array, Phaser.Utils.Objects, and Phaser.Utils.String helper functions.1112**Related skills:** ../groups-and-containers/SKILL.md, ../sprites-and-images/SKILL.md1314---1516## Quick Start1718```js19// Create 20 sprites and batch-position them in a grid20const sprites = [];21for (let i = 0; i < 20; i++) {22 sprites.push(this.add.sprite(0, 0, 'gem'));23}2425// Arrange into a 5x4 grid26Phaser.Actions.GridAlign(sprites, {27 width: 5,28 height: 4,29 cellWidth: 64,30 cellHeight: 64,31 x: 100,32 y: 10033});3435// Fade alpha from 0 to 1 across all sprites36Phaser.Actions.Spread(sprites, 'alpha', 0, 1);3738// Offset each sprite's x by 10, with a step of 2 per item39Phaser.Actions.IncX(sprites, 10, 2);4041// Works with Groups too42const group = this.add.group({ key: 'star', repeat: 11 });43Phaser.Actions.PlaceOnCircle(group.getChildren(), new Phaser.Geom.Circle(400, 300, 200));44```4546---4748## Core Concepts4950### The Actions Pattern5152Every Action in `Phaser.Actions` follows the same pattern:53541. **First argument is always an array** of Game Objects (or any objects with the required public properties like `x`, `y`, `alpha`, etc.).552. **Returns the same array**, enabling chaining or pass-through.563. **Works with Groups** by passing `group.getChildren()`.574. Actions do NOT store state. They are one-shot batch operations.5859### PropertyValueSet and PropertyValueInc6061Most Set/Inc actions delegate to two core functions:6263- **`PropertyValueSet(items, key, value, step, index, direction)`** -- Sets `items[i][key] = value + (i * step)`.64- **`PropertyValueInc(items, key, value, step, index, direction)`** -- Adds `items[i][key] += value + (i * step)`.6566The `step` parameter adds an incremental offset per item. The `index` and `direction` parameters control iteration start point and order (1 = forward, -1 = backward).6768### Geometry-Based Placement6970Actions 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.7172---7374## All Actions7576### Property Setters7778| Action | Signature | Description |79|---|---|---|80| `SetX` | `(items, value, step?, index?, direction?)` | Set `x` property |81| `SetY` | `(items, value, step?, index?, direction?)` | Set `y` property |82| `SetXY` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Set both `x` and `y`; `y` defaults to `x` |83| `SetAlpha` | `(items, value, step?, index?, direction?)` | Set `alpha` |84| `SetBlendMode` | `(items, value, index?, direction?)` | Set blend mode |85| `SetDepth` | `(items, value, step?, index?, direction?)` | Set render depth |86| `SetHitArea` | `(items, hitArea?, callback?)` | Set interactive hit area |87| `SetOrigin` | `(items, originX, originY?, stepX?, stepY?, index?, direction?)` | Set origin point |88| `SetRotation` | `(items, value, step?, index?, direction?)` | Set rotation (radians) |89| `SetScale` | `(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)` | Set both scale axes |90| `SetScaleX` | `(items, value, step?, index?, direction?)` | Set `scaleX` |91| `SetScaleY` | `(items, value, step?, index?, direction?)` | Set `scaleY` |92| `SetScrollFactor` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Set scroll factor |93| `SetScrollFactorX` | `(items, value, step?, index?, direction?)` | Set horizontal scroll factor |94| `SetScrollFactorY` | `(items, value, step?, index?, direction?)` | Set vertical scroll factor |95| `SetTint` | `(items, topLeft, topRight?, bottomLeft?, bottomRight?)` | Set tint color(s) |96| `SetVisible` | `(items, value, index?, direction?)` | Set visibility |97| `PropertyValueSet` | `(items, key, value, step?, index?, direction?)` | Generic: set any named property |9899### Property Incrementers100101| Action | Signature | Description |102|---|---|---|103| `IncX` | `(items, value, step?, index?, direction?)` | Add to `x` |104| `IncXY` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Add to `x` and `y` |105| `IncY` | `(items, value, step?, index?, direction?)` | Add to `y` |106| `IncAlpha` | `(items, value, step?, index?, direction?)` | Add to `alpha` |107| `Angle` | `(items, value, step?, index?, direction?)` | Add to `angle` (degrees) |108| `Rotate` | `(items, value, step?, index?, direction?)` | Add to `rotation` (radians) |109| `ScaleX` | `(items, value, step?, index?, direction?)` | Add to `scaleX` |110| `ScaleXY` | `(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)` | Add to both scale axes |111| `ScaleY` | `(items, value, step?, index?, direction?)` | Add to `scaleY` |112| `PropertyValueInc` | `(items, key, value, step?, index?, direction?)` | Generic: increment any named property |113114### Placement on Geometry115116| Action | Signature | Description |117|---|---|---|118| `PlaceOnCircle` | `(items, circle, startAngle?, endAngle?)` | Evenly space on circle perimeter |119| `PlaceOnEllipse` | `(items, ellipse, startAngle?, endAngle?)` | Evenly space on ellipse perimeter |120| `PlaceOnLine` | `(items, line)` | Evenly space along a line |121| `PlaceOnRectangle` | `(items, rect, shift?)` | Evenly space on rectangle perimeter |122| `PlaceOnTriangle` | `(items, triangle, stepRate?)` | Evenly space on triangle perimeter |123| `RandomCircle` | `(items, circle)` | Random positions within a circle |124| `RandomEllipse` | `(items, ellipse)` | Random positions within an ellipse |125| `RandomLine` | `(items, line)` | Random positions along a line |126| `RandomRectangle` | `(items, rect)` | Random positions within a rectangle |127| `RandomTriangle` | `(items, triangle)` | Random positions within a triangle |128129### Layout and Alignment130131| Action | Signature | Description |132|---|---|---|133| `GridAlign` | `(items, config)` | Arrange in grid; config: `{ width, height, cellWidth, cellHeight, position, x, y }` |134| `AlignTo` | `(items, position, offsetX?, offsetY?)` | Chain-align each item next to the previous one using `Phaser.Display.Align` constants |135| `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 |136137### Distribution and Interpolation138139| Action | Signature | Description |140|---|---|---|141| `Spread` | `(items, property, min, max, inc?)` | Linearly distribute a property from `min` to `max` across all items |142| `SmoothStep` | `(items, property, min, max, inc?)` | Distribute using Hermite smoothstep interpolation |143| `SmootherStep` | `(items, property, min, max, inc?)` | Distribute using Ken Perlin's smootherstep |144145### Rotation and Movement146147| Action | Signature | Description |148|---|---|---|149| `RotateAround` | `(items, point, angle)` | Rotate all items around a point (radians) |150| `RotateAroundDistance` | `(items, point, angle, distance)` | Rotate around a point at a fixed distance |151| `ShiftPosition` | `(items, x, y, direction?, output?)` | Snake-like: move head to x/y, each item takes position of the previous |152| `WrapInRectangle` | `(items, rect, padding?)` | Wrap x/y to stay within rectangle bounds |153154### Queries and Iteration155156| Action | Signature | Description |157|---|---|---|158| `GetFirst` | `(items, compare, index?)` | Find first item matching all properties in `compare` object |159| `GetLast` | `(items, compare, index?)` | Find last item matching all properties in `compare` object |160| `Call` | `(items, callback, context)` | Invoke callback for each item |161| `Shuffle` | `(items)` | Randomly reorder the array (Fisher-Yates) |162| `ToggleVisible` | `(items)` | Toggle `visible` on each item |163| `PlayAnimation` | `(items, key, ignoreIfPlaying?)` | Play animation on all items with an `anims` component |164165### Effects (v4.0.0+)166167| Action | Signature | Description |168|---|---|---|169| `AddEffectBloom` | `(items, config?)` | Add Bloom filter effect to a Camera or GO. Returns `{ parallelFilters, threshold, blur }[]` |170| `AddEffectShine` | `(items, config?)` | Add Shine filter effect |171| `AddMaskShape` | `(items, config?)` | Apply a shape-based mask (circle, square, rectangle, ellipse) with optional blur |172173---174175## Array Utilities176177Namespace: `Phaser.Utils.Array`178179| Function | Signature | Description |180|---|---|---|181| `Add` | `(array, item, limit?, callback?, context?)` | Add item(s) if not already present; optional size limit |182| `AddAt` | `(array, item, index?, limit?, callback?, context?)` | Insert item(s) at index |183| `BringToTop` | `(array, item)` | Move item to end of array |184| `CountAllMatching` | `(array, property, value, startIndex?, endIndex?)` | Count items where property equals value |185| `Each` | `(array, callback, context, ...args)` | Iterate with callback; passes item + extra args |186| `EachInRange` | `(array, callback, context, startIndex, endIndex, ...args)` | Iterate a slice with callback |187| `FindClosestInSorted` | `(value, array, key?)` | Binary-search style closest match in sorted array |188| `Flatten` | `(array, output?)` | Flatten nested arrays into a single array |189| `GetAll` | `(array, property?, value?, startIndex?, endIndex?)` | Filter items matching property/value |190| `GetFirst` | `(array, property?, value?, startIndex?, endIndex?)` | First item matching property/value |191| `GetRandom` | `(array, startIndex?, length?)` | Return a random element |192| `MoveAbove` | `(array, item1, item2)` | Move item2 directly above item1 |193| `MoveBelow` | `(array, item1, item2)` | Move item2 directly below item1 |194| `MoveDown` | `(array, item)` | Move item one position toward index 0 |195| `MoveTo` | `(array, item, index)` | Move item to specific index |196| `MoveUp` | `(array, item)` | Move item one position toward end |197| `NumberArray` | `(start, end, prefix?, suffix?)` | Generate `[start..end]` range; optional string prefix/suffix |198| `NumberArrayStep` | `(start?, end?, step?)` | Generate range with custom step size |199| `QuickSelect` | `(array, k, left?, right?, compare?)` | Partial sort: kth smallest element in-place |200| `Range` | `(a, b, options?)` | Generate array from range config |201| `Remove` | `(array, item, callback?, context?)` | Remove item(s) from array |202| `RemoveAt` | `(array, index, callback?, context?)` | Remove item at index |203| `RemoveBetween` | `(array, startIndex, endIndex, callback?, context?)` | Remove items in range |204| `RemoveRandomElement` | `(array, startIndex?, length?)` | Remove and return a random element |205| `Replace` | `(array, oldItem, newItem)` | Swap one item for another |206| `RotateLeft` | `(array, total?)` | Shift elements left; last wraps to front |207| `RotateRight` | `(array, total?)` | Shift elements right; first wraps to end |208| `SafeRange` | `(array, startIndex, endIndex, throwError?)` | Validate index range is within bounds |209| `SendToBack` | `(array, item)` | Move item to index 0 |210| `SetAll` | `(array, property, value, startIndex?, endIndex?)` | Set a property on all items in range |211| `Shuffle` | `(array)` | Fisher-Yates shuffle; modifies in-place |212| `SortByDigits` | `(array)` | Sort strings by embedded numeric values |213| `SpliceOne` | `(array, index)` | Fast single-element splice |214| `StableSort` | `(array, compare?)` | Guaranteed stable sort (merge sort fallback for engines without native stable sort) |215| `Swap` | `(array, item1, item2)` | Swap two items in-place |216217Also includes `Phaser.Utils.Array.Matrix` sub-namespace for 2D matrix operations.218219---220221## Object Utilities222223Namespace: `Phaser.Utils.Objects`224225| Function | Signature | Description |226|---|---|---|227| `Clone` | `(obj)` | Shallow clone of object |228| `DeepCopy` | `(obj)` | Recursive deep copy of object or array |229| `Extend` | `(target, ...sources)` | jQuery-style extend; copies properties from sources to target |230| `GetAdvancedValue` | `(source, key, defaultValue)` | Like `GetValue` but resolves random/callback config values |231| `GetFastValue` | `(source, key, defaultValue?)` | Top-level-only property lookup; no dot-path support. Faster than `GetValue` |232| `GetMinMaxValue` | `(source, key, min, max, defaultValue)` | Get value clamped between min and max |233| `GetValue` | `(source, key, defaultValue, altSource?)` | Dot-path property lookup (e.g. `'render.screen.width'`). Falls back to altSource then defaultValue |234| `HasAll` | `(source, keys)` | True if source has ALL listed keys |235| `HasAny` | `(source, keys)` | True if source has ANY listed key |236| `HasValue` | `(source, key)` | True if source has the key |237| `IsPlainObject` | `(obj)` | True if obj is a plain `{}` object (not DOM, not window) |238| `Merge` | `(obj1, obj2)` | Merge obj2 into a clone of obj1 |239| `MergeRight` | `(obj1, obj2)` | Merge obj1 into a clone of obj2 |240| `Pick` | `(source, keys)` | Return new object with only the specified keys |241| `SetValue` | `(source, key, value)` | Set a dot-path property value |242243---244245## String Utilities246247Namespace: `Phaser.Utils.String`248249| Function | Signature | Description |250|---|---|---|251| `Format` | `(string, values)` | Replace `%1`, `%2`, etc. markers with array values |252| `Pad` | `(str, len?, pad?, dir?)` | Pad string to length. dir: 1=left, 2=right, default=both |253| `RemoveAt` | `(string, index)` | Remove character at index |254| `Reverse` | `(string)` | Reverse the string |255| `UppercaseFirst` | `(string)` | Capitalize first character |256| `UUID` | `()` | Generate RFC4122 v4 UUID string |257258---259260## Common Patterns261262### Using Actions with Groups263264```js265const enemies = this.add.group({ key: 'enemy', repeat: 9 });266267// Position all children in a grid268Phaser.Actions.GridAlign(enemies.getChildren(), {269 width: 5, height: 2,270 cellWidth: 80, cellHeight: 80,271 x: 100, y: 50272});273274// Fan out alpha across all enemies275Phaser.Actions.Spread(enemies.getChildren(), 'alpha', 0.3, 1);276```277278### Step Parameter for Staggered Values279280```js281// Place sprites starting at x=100, each one 50px further right282Phaser.Actions.SetX(sprites, 100, 50);283// Result: items[0].x=100, items[1].x=150, items[2].x=200, ...284285// Increment rotation with increasing step286Phaser.Actions.Rotate(sprites, 0.1, 0.05);287// Result: items[0].rotation += 0.1, items[1].rotation += 0.15, items[2].rotation += 0.2, ...288```289290### Scatter Then Constrain291292```js293const bounds = new Phaser.Geom.Rectangle(0, 0, 800, 600);294// Random scatter295Phaser.Actions.RandomRectangle(sprites, bounds);296// Keep wrapped in bounds during update297Phaser.Actions.WrapInRectangle(sprites, bounds);298```299300### GetValue for Config Parsing301302```js303// Deep property access with fallback304const width = Phaser.Utils.Objects.GetValue(config, 'render.screen.width', 800);305306// Fast top-level lookup (no dot-path, better performance)307const speed = Phaser.Utils.Objects.GetFastValue(config, 'speed', 100);308```309310### NumberArray for Asset Keys311312```js313// Generate frame key strings314const keys = Phaser.Utils.Array.NumberArray(1, 10, 'frame_', '.png');315// Result: ['frame_1.png', 'frame_2.png', ..., 'frame_10.png']316```317318---319320## Gotchas321322- **Actions operate on plain arrays, not Groups directly.** Always call `group.getChildren()` to get the array.323- **PlaceOn/Random geometry actions need `Phaser.Geom` objects**, not Game Object shapes. For a `Phaser.GameObjects.Circle`, pass `circle.geom`.324- **`SetXY` defaults `y` to `x`** if `y` is `undefined` or `null`. Pass `0` explicitly if you want y=0 and x=something else.325- **`Spread` with a single item** places it at the midpoint `(min + max) / 2`, not at `min`.326- **`step` is multiplied by iteration index**, not added cumulatively. Item 0 gets `value + 0*step`, item 1 gets `value + 1*step`, etc.327- **`StableSort` uses native `Array.sort` when the engine supports stable sorting**, falling back to merge sort only when needed.328- **`Shuffle` (both Actions and Utils.Array) modifies the array in-place** and returns it.329- **`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.330- **`AddEffectBloom` / `AddEffectShine` / `AddMaskShape` are v4-only** filter-based effects. They return arrays of created effects instead of the input.331332---333334## Source File Map335336| Area | Path |337|---|---|338| All Actions | `src/actions/` |339| Actions index | `src/actions/index.js` |340| Core set/inc helpers | `src/actions/PropertyValueSet.js`, `src/actions/PropertyValueInc.js` |341| GridAlign config typedef | `src/actions/typedefs/` |342| Array utilities | `src/utils/array/` |343| Array matrix utils | `src/utils/array/matrix/` |344| Object utilities | `src/utils/object/` |345| String utilities | `src/utils/string/` |