phaserjs/phaser · error · Error

GetCentroid points be a non-empty array

Error message

GetCentroid points be a non-empty array

What it means

GetCentroid.js:31 throws when `points` is not an array or is an empty array. The function averages all point coordinates to find the geometric center, so it needs at least one valid `{x, y}` point. The guard checks both `Array.isArray(points)` and `len === 0`.

Source

Thrown at src/math/GetCentroid.js:31

 * @function Phaser.Math.GetCentroid
 * @since 4.0.0
 *
 * @generic {Phaser.Math.Vector2} O - [out,$return]
 *
 * @param {Phaser.Types.Math.Vector2Like[]} points - An array of Vector2Like objects to get the geometric center of.
 * @param {Phaser.Math.Vector2} [out] - A Vector2 object to store the output coordinates in. If not given, a new Vector2 instance is created.
 *
 * @return {Phaser.Math.Vector2} A Vector2 object representing the geometric center of the given points.
 */
var GetCentroid = function (points, out)
{
    if (out === undefined) { out = new Vector2(); }

    var len = points.length;

    if (!Array.isArray(points) || len === 0)
    {
        throw new Error('GetCentroid points be a non-empty array');
    }

    if (len === 1)
    {
        out.x = points[0].x;
        out.y = points[0].y;
    }
    else
    {
        for (var i = 0; i < len; i++)
        {
            out.x += points[i].x;
            out.y += points[i].y;
        }

        out.x /= len;
        out.y /= len;
    }

View on GitHub (pinned to 41be1e462b)

Solutions

  1. Guard the call site: only invoke GetCentroid when `Array.isArray(points) && points.length > 0`.
  2. Provide a default non-empty points array as the function's `out`/fallback.
  3. Fix the upstream logic producing the empty array.

Example fix

// before
const c = Phaser.Math.GetCentroid(filteredPoints)
// after
const c = filteredPoints.length ? Phaser.Math.GetCentroid(filteredPoints) : new Phaser.Math.Vector2(0, 0)
Defensive patterns

Strategy: type-guard

Validate before calling

if (!Array.isArray(points) || points.length === 0) {
  return new Phaser.Math.Vector2(0, 0)
}
return Phaser.Math.GetCentroid(points)

Type guard

const isNonEmptyPointArray = (p) => Array.isArray(p) && p.length > 0 && p.every(pt => pt && typeof pt.x === 'number' && typeof pt.y === 'number')

Prevention

When it happens

Trigger: Calling `Phaser.Geom.Point.GetCentroid(points)` (or `Phaser.Math.GetCentroid`) with `points = []`, `points = undefined`, or `points = null`. Also passing a non-array iterable (Set/Map values) which fails `Array.isArray`.

Common situations: Computing a centroid from a polygon/vertex list that was filtered to empty; passing the result of a `.filter()`/`.map()` that returned no items; deserialising geometry data that came back empty.

Related errors


AI-assisted analysis of phaserjs/phaser@41be1e462b (2026-08-13). Data as JSON: /api/errors/e13309e240779b19. Report an issue: GitHub.