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.4---56# Phaser 4 -- Actions & Utility Functions78> Phaser.Actions namespace for batch operations on Game Object arrays, plus Phaser.Utils.Array, Phaser.Utils.Objects, and Phaser.Utils.String helper functions.910**Related skills:** ../groups-and-containers/SKILL.md, ../sprites-and-images/SKILL.md1112---1314## Quick Start1516```js17// Create 20 sprites and batch-position them in a grid18const sprites = [];19for (let i = 0; i < 20; i++) {20 sprites.push(this.add.sprite(0, 0, 'gem'));21}2223// Arrange into a 5x4 grid24Phaser.Actions.GridAlign(sprites, {25 width: 5,26 height: 4,27 cellWidth: 64,28 cellHeight: 64,29 x: 100,30 y: 10031});3233// Fade alpha from 0 to 1 across all sprites34Phaser.Actions.Spread(sprites, 'alpha', 0, 1);3536// Offset each sprite's x by 10, with a step of 2 per item37Phaser.Actions.IncX(sprites, 10, 2);3839// Works with Groups too40const group = this.add.group({ key: 'star', repeat: 11 });41Phaser.Actions.PlaceOnCircle(group.getChildren(), new Phaser.Geom.Circle(400, 300, 200));42```4344---4546## Core Concepts4748### The Actions Pattern4950Every Action in `Phaser.Actions` follows the same pattern:51521. **First argument is always an array** of Game Objects (or any objects with the required public properties like `x`, `y`, `alpha`, etc.).532. **Returns the same array**, enabling chaining or pass-through.543. **Works with Groups** by passing `group.getChildren()`.554. Actions do NOT store state. They are one-shot batch operations.5657### PropertyValueSet and PropertyValueInc5859Most Set/Inc actions delegate to two core functions:6061- **`PropertyValueSet(items, key, value, step, index, direction)`** -- Sets `items[i][key] = value + (i * step)`.62- **`PropertyValueInc(items, key, value, step, index, direction)`** -- Adds `items[i][key] += value + (i * step)`.6364The `step` parameter adds an incremental offset per item. The `index` and `direction` parameters control iteration start point and order (1 = forward, -1 = backward).6566### Geometry-Based Placement6768Actions 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.6970---7172## All Actions7374### Property Setters7576| Action | Signature | Description |77|---|---|---|78| `SetX` | `(items, value, step?, index?, direction?)` | Set `x` property |79| `SetY` | `(items, value, step?, index?, direction?)` | Set `y` property |80| `SetXY` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Set both `x` and `y`; `y` defaults to `x` |81| `SetAlpha` | `(items, value, step?, index?, direction?)` | Set `alpha` |82| `SetBlendMode` | `(items, value, index?, direction?)` | Set blend mode |83| `SetDepth` | `(items, value, step?, index?, direction?)` | Set render depth |84| `SetHitArea` | `(items, hitArea?, callback?)` | Set interactive hit area |85| `SetOrigin` | `(items, originX, originY?, stepX?, stepY?, index?, direction?)` | Set origin point |86| `SetRotation` | `(items, value, step?, index?, direction?)` | Set rotation (radians) |87| `SetScale` | `(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)` | Set both scale axes |88| `SetScaleX` | `(items, value, step?, index?, direction?)` | Set `scaleX` |89| `SetScaleY` | `(items, value, step?, index?, direction?)` | Set `scaleY` |90| `SetScrollFactor` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Set scroll factor |91| `SetScrollFactorX` | `(items, value, step?, index?, direction?)` | Set horizontal scroll factor |92| `SetScrollFactorY` | `(items, value, step?, index?, direction?)` | Set vertical scroll factor |93| `SetTint` | `(items, topLeft, topRight?, bottomLeft?, bottomRight?)` | Set tint color(s) |94| `SetVisible` | `(items, value, index?, direction?)` | Set visibility |95| `PropertyValueSet` | `(items, key, value, step?, index?, direction?)` | Generic: set any named property |9697### Property Incrementers9899| Action | Signature | Description |100|---|---|---|101| `IncX` | `(items, value, step?, index?, direction?)` | Add to `x` |102| `IncXY` | `(items, x, y?, stepX?, stepY?, index?, direction?)` | Add to `x` and `y` |103| `IncY` | `(items, value, step?, index?, direction?)` | Add to `y` |104| `IncAlpha` | `(items, value, step?, index?, direction?)` | Add to `alpha` |105| `Angle` | `(items, value, step?, index?, direction?)` | Add to `angle` (degrees) |106| `Rotate` | `(items, value, step?, index?, direction?)` | Add to `rotation` (radians) |107| `ScaleX` | `(items, value, step?, index?, direction?)` | Add to `scaleX` |108| `ScaleXY` | `(items, scaleX, scaleY?, stepX?, stepY?, index?, direction?)` | Add to both scale axes |109| `ScaleY` | `(items, value, step?, index?, direction?)` | Add to `scaleY` |110| `PropertyValueInc` | `(items, key, value, step?, index?, direction?)` | Generic: increment any named property |111112### Placement on Geometry113114| Action | Signature | Description |115|---|---|---|116| `PlaceOnCircle` | `(items, circle, startAngle?, endAngle?)` | Evenly space on circle perimeter |117| `PlaceOnEllipse` | `(items, ellipse, startAngle?, endAngle?)` | Evenly space on ellipse perimeter |118| `PlaceOnLine` | `(items, line)` | Evenly space along a line |119| `PlaceOnRectangle` | `(items, rect, shift?)` | Evenly space on rectangle perimeter |120| `PlaceOnTriangle` | `(items, triangle, stepRate?)` | Evenly space on triangle perimeter |121| `RandomCircle` | `(items, circle)` | Random positions within a circle |122| `RandomEllipse` | `(items, ellipse)` | Random positions within an ellipse |123| `RandomLine` | `(items, line)` | Random positions along a line |124| `RandomRectangle` | `(items, rect)` | Random positions within a rectangle |125| `RandomTriangle` | `(items, triangle)` | Random positions within a triangle |126127### Layout and Alignment128129| Action | Signature | Description |130|---|---|---|131| `GridAlign` | `(items, config)` | Arrange in grid; config: `{ width, height, cellWidth, cellHeight, position, x, y }` |132| `AlignTo` | `(items, position, offsetX?, offsetY?)` | Chain-align each item next to the previous one using `Phaser.Display.Align` constants |133| `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 |134135### Distribution and Interpolation136137| Action | Signature | Description |138|---|---|---|139| `Spread` | `(items, property, min, max, inc?)` | Linearly distribute a property from `min` to `max` across all items |140| `SmoothStep` | `(items, property, min, max, inc?)` | Distribute using Hermite smoothstep interpolation |141| `SmootherStep` | `(items, property, min, max, inc?)` | Distribute using Ken Perlin's smootherstep |142143### Rotation and Movement144145| Action | Signature | Description |146|---|---|---|147| `RotateAround` | `(items, point, angle)` | Rotate all items around a point (radians) |148| `RotateAroundDistance` | `(items, point, angle, distance)` | Rotate around a point at a fixed distance |149| `ShiftPosition` | `(items, x, y, direction?, output?)` | Snake-like: move head to x/y, each item takes position of the previous |150| `WrapInRectangle` | `(items, rect, padding?)` | Wrap x/y to stay within rectangle bounds |151152### Queries and Iteration153154| Action | Signature | Description |155|---|---|---|156| `GetFirst` | `(items, compare, index?)` | Find first item matching all properties in `compare` object |157| `GetLast` | `(items, compare, index?)` | Find last item matching all properties in `compare` object |158| `Call` | `(items, callback, context)` | Invoke callback for each item |159| `Shuffle` | `(items)` | Randomly reorder the array (Fisher-Yates) |160| `ToggleVisible` | `(items)` | Toggle `visible` on each item |161| `PlayAnimation` | `(items, key, ignoreIfPlaying?)` | Play animation on all items with an `anims` component |162163### Effects (v4.0.0+)164165| Action | Signature | Description |166|---|---|---|167| `AddEffectBloom` | `(items, config?)` | Add Bloom filter effect to a Camera or GO. Returns `{ parallelFilters, threshold, blur }[]` |168| `AddEffectShine` | `(items, config?)` | Add Shine filter effect |169| `AddMaskShape` | `(items, config?)` | Apply a shape-based mask (circle, square, rectangle, ellipse) with optional blur |170171---172173## Array Utilities174175Namespace: `Phaser.Utils.Array`176177| Function | Signature | Description |178|---|---|---|179| `Add` | `(array, item, limit?, callback?, context?)` | Add item(s) if not already present; optional size limit |180| `AddAt` | `(array, item, index?, limit?, callback?, context?)` | Insert item(s) at index |181| `BringToTop` | `(array, item)` | Move item to end of array |182| `CountAllMatching` | `(array, property, value, startIndex?, endIndex?)` | Count items where property equals value |183| `Each` | `(array, callback, context, ...args)` | Iterate with callback; passes item + extra args |184| `EachInRange` | `(array, callback, context, startIndex, endIndex, ...args)` | Iterate a slice with callback |185| `FindClosestInSorted` | `(value, array, key?)` | Binary-search style closest match in sorted array |186| `Flatten` | `(array, output?)` | Flatten nested arrays into a single array |187| `GetAll` | `(array, property?, value?, startIndex?, endIndex?)` | Filter items matching property/value |188| `GetFirst` | `(array, property?, value?, startIndex?, endIndex?)` | First item matching property/value |189| `GetRandom` | `(array, startIndex?, length?)` | Return a random element |190| `MoveAbove` | `(array, item1, item2)` | Move item2 directly above item1 |191| `MoveBelow` | `(array, item1, item2)` | Move item2 directly below item1 |192| `MoveDown` | `(array, item)` | Move item one position toward index 0 |193| `MoveTo` | `(array, item, index)` | Move item to specific index |194| `MoveUp` | `(array, item)` | Move item one position toward end |195| `NumberArray` | `(start, end, prefix?, suffix?)` | Generate `[start..end]` range; optional string prefix/suffix |196| `NumberArrayStep` | `(start?, end?, step?)` | Generate range with custom step size |197| `QuickSelect` | `(array, k, left?, right?, compare?)` | Partial sort: kth smallest element in-place |198| `Range` | `(a, b, options?)` | Generate array from range config |199| `Remove` | `(array, item, callback?, context?)` | Remove item(s) from array |200| `RemoveAt` | `(array, index, callback?, context?)` | Remove item at index |201| `RemoveBetween` | `(array, startIndex, endIndex, callback?, context?)` | Remove items in range |202| `RemoveRandomElement` | `(array, startIndex?, length?)` | Remove and return a random element |203| `Replace` | `(array, oldItem, newItem)` | Swap one item for another |204| `RotateLeft` | `(array, total?)` | Shift elements left; last wraps to front |205| `RotateRight` | `(array, total?)` | Shift elements right; first wraps to end |206| `SafeRange` | `(array, startIndex, endIndex, throwError?)` | Validate index range is within bounds |207| `SendToBack` | `(array, item)` | Move item to index 0 |208| `SetAll` | `(array, property, value, startIndex?, endIndex?)` | Set a property on all items in range |209| `Shuffle` | `(array)` | Fisher-Yates shuffle; modifies in-place |210| `SortByDigits` | `(array)` | Sort strings by embedded numeric values |211| `SpliceOne` | `(array, index)` | Fast single-element splice |212| `StableSort` | `(array, compare?)` | Guaranteed stable sort (merge sort fallback for engines without native stable sort) |213| `Swap` | `(array, item1, item2)` | Swap two items in-place |214215Also includes `Phaser.Utils.Array.Matrix` sub-namespace for 2D matrix operations.216217---218219## Object Utilities220221Namespace: `Phaser.Utils.Objects`222223| Function | Signature | Description |224|---|---|---|225| `Clone` | `(obj)` | Shallow clone of object |226| `DeepCopy` | `(obj)` | Recursive deep copy of object or array |227| `Extend` | `(target, ...sources)` | jQuery-style extend; copies properties from sources to target |228| `GetAdvancedValue` | `(source, key, defaultValue)` | Like `GetValue` but resolves random/callback config values |229| `GetFastValue` | `(source, key, defaultValue?)` | Top-level-only property lookup; no dot-path support. Faster than `GetValue` |230| `GetMinMaxValue` | `(source, key, min, max, defaultValue)` | Get value clamped between min and max |231| `GetValue` | `(source, key, defaultValue, altSource?)` | Dot-path property lookup (e.g. `'render.screen.width'`). Falls back to altSource then defaultValue |232| `HasAll` | `(source, keys)` | True if source has ALL listed keys |233| `HasAny` | `(source, keys)` | True if source has ANY listed key |234| `HasValue` | `(source, key)` | True if source has the key |235| `IsPlainObject` | `(obj)` | True if obj is a plain `{}` object (not DOM, not window) |236| `Merge` | `(obj1, obj2)` | Merge obj2 into a clone of obj1 |237| `MergeRight` | `(obj1, obj2)` | Merge obj1 into a clone of obj2 |238| `Pick` | `(source, keys)` | Return new object with only the specified keys |239| `SetValue` | `(source, key, value)` | Set a dot-path property value |240241---242243## String Utilities244245Namespace: `Phaser.Utils.String`246247| Function | Signature | Description |248|---|---|---|249| `Format` | `(string, values)` | Replace `%1`, `%2`, etc. markers with array values |250| `Pad` | `(str, len?, pad?, dir?)` | Pad string to length. dir: 1=left, 2=right, default=both |251| `RemoveAt` | `(string, index)` | Remove character at index |252| `Reverse` | `(string)` | Reverse the string |253| `UppercaseFirst` | `(string)` | Capitalize first character |254| `UUID` | `()` | Generate RFC4122 v4 UUID string |255256---257258## Common Patterns259260### Using Actions with Groups261262```js263const enemies = this.add.group({ key: 'enemy', repeat: 9 });264265// Position all children in a grid266Phaser.Actions.GridAlign(enemies.getChildren(), {267 width: 5, height: 2,268 cellWidth: 80, cellHeight: 80,269 x: 100, y: 50270});271272// Fan out alpha across all enemies273Phaser.Actions.Spread(enemies.getChildren(), 'alpha', 0.3, 1);274```275276### Step Parameter for Staggered Values277278```js279// Place sprites starting at x=100, each one 50px further right280Phaser.Actions.SetX(sprites, 100, 50);281// Result: items[0].x=100, items[1].x=150, items[2].x=200, ...282283// Increment rotation with increasing step284Phaser.Actions.Rotate(sprites, 0.1, 0.05);285// Result: items[0].rotation += 0.1, items[1].rotation += 0.15, items[2].rotation += 0.2, ...286```287288### Scatter Then Constrain289290```js291const bounds = new Phaser.Geom.Rectangle(0, 0, 800, 600);292// Random scatter293Phaser.Actions.RandomRectangle(sprites, bounds);294// Keep wrapped in bounds during update295Phaser.Actions.WrapInRectangle(sprites, bounds);296```297298### GetValue for Config Parsing299300```js301// Deep property access with fallback302const width = Phaser.Utils.Objects.GetValue(config, 'render.screen.width', 800);303304// Fast top-level lookup (no dot-path, better performance)305const speed = Phaser.Utils.Objects.GetFastValue(config, 'speed', 100);306```307308### NumberArray for Asset Keys309310```js311// Generate frame key strings312const keys = Phaser.Utils.Array.NumberArray(1, 10, 'frame_', '.png');313// Result: ['frame_1.png', 'frame_2.png', ..., 'frame_10.png']314```315316---317318## Gotchas319320- **Actions operate on plain arrays, not Groups directly.** Always call `group.getChildren()` to get the array.321- **PlaceOn/Random geometry actions need `Phaser.Geom` objects**, not Game Object shapes. For a `Phaser.GameObjects.Circle`, pass `circle.geom`.322- **`SetXY` defaults `y` to `x`** if `y` is `undefined` or `null`. Pass `0` explicitly if you want y=0 and x=something else.323- **`Spread` with a single item** places it at the midpoint `(min + max) / 2`, not at `min`.324- **`step` is multiplied by iteration index**, not added cumulatively. Item 0 gets `value + 0*step`, item 1 gets `value + 1*step`, etc.325- **`StableSort` uses native `Array.sort` when the engine supports stable sorting**, falling back to merge sort only when needed.326- **`Shuffle` (both Actions and Utils.Array) modifies the array in-place** and returns it.327- **`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.328- **`AddEffectBloom` / `AddEffectShine` / `AddMaskShape` are v4-only** filter-based effects. They return arrays of created effects instead of the input.329330---331332## Source File Map333334| Area | Path |335|---|---|336| All Actions | `src/actions/` |337| Actions index | `src/actions/index.js` |338| Core set/inc helpers | `src/actions/PropertyValueSet.js`, `src/actions/PropertyValueInc.js` |339| GridAlign config typedef | `src/actions/typedefs/` |340| Array utilities | `src/utils/array/` |341| Array matrix utils | `src/utils/array/matrix/` |342| Object utilities | `src/utils/object/` |343| String utilities | `src/utils/string/` |