Skip to content

Commit 5e2e520

Browse files
committed
Added Phaser.Point.centroid function.
Added static Phaser.Point.centroid function to calculate the centroid or midpoint of an array of points.
1 parent 3f8911d commit 5e2e520

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

src/geom/Point.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,5 +455,40 @@ Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
455455

456456
};
457457

458+
/**
459+
* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
460+
* @method Phaser.Point.centroid
461+
* @param {Phaser.Point[]} points - The array of one or more points.
462+
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
463+
* @return {Phaser.Point} The new Point object.
464+
*/
465+
Phaser.Point.centroid = function (points, out) {
466+
467+
if (typeof out === "undefined") { out = new Phaser.Point(); }
468+
469+
if (Object.prototype.toString.call(points) !== '[object Array]') {
470+
throw new Error("Phaser.Point. Parameter 'points' must be an array")
471+
}
472+
473+
if (points.length < 1) {
474+
throw new Error("Phaser.Point. Parameter 'points' array must not be empty")
475+
}
476+
477+
if (points.length === 1) {
478+
out.copyFrom(points[0]);
479+
return out;
480+
}
481+
482+
var totalpoints = Math.round(points.length / 2);
483+
484+
for (var i = 0; i < points.length; i++) {
485+
Phaser.Point.add(out, points[i], out);
486+
}
487+
488+
out.divide(totalpoints, totalpoints);
489+
490+
return out;
491+
};
492+
458493
// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
459494
PIXI.Point = Phaser.Point;

0 commit comments

Comments
 (0)