|
| 1 | +/** |
| 2 | + * @author Richard Davey <rich@photonstorm.com> |
| 3 | + * @copyright 2018 Photon Storm Ltd. |
| 4 | + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} |
| 5 | + */ |
| 6 | + |
| 7 | +var Length = require('../line/Length'); |
| 8 | +var Line = require('../line/Line'); |
| 9 | +var Perimeter = require('./Perimeter'); |
| 10 | + |
| 11 | +/** |
| 12 | + * Returns an array of Point objects containing the coordinates of the points around the perimeter of the Polygon, |
| 13 | + * based on the given quantity or stepRate values. |
| 14 | + * |
| 15 | + * @function Phaser.Geom.Polygon.GetPoints |
| 16 | + * @since 3.12.0 |
| 17 | + * |
| 18 | + * @param {Phaser.Geom.Polygon} polygon - The Polygon to get the points from. |
| 19 | + * @param {integer} quantity - The amount of points to return. If a falsey value the quantity will be derived from the `stepRate` instead. |
| 20 | + * @param {number} [stepRate] - Sets the quantity by getting the perimeter of the Polygon and dividing it by the stepRate. |
| 21 | + * @param {array} [output] - An array to insert the points in to. If not provided a new array will be created. |
| 22 | + * |
| 23 | + * @return {Phaser.Geom.Point[]} An array of Point objects pertaining to the points around the perimeter of the Polygon. |
| 24 | + */ |
| 25 | +var GetPoints = function (polygon, quantity, stepRate, out) |
| 26 | +{ |
| 27 | + if (out === undefined) { out = []; } |
| 28 | + |
| 29 | + var points = polygon.points; |
| 30 | + var perimeter = Perimeter(polygon); |
| 31 | + |
| 32 | + // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. |
| 33 | + if (!quantity) |
| 34 | + { |
| 35 | + quantity = perimeter / stepRate; |
| 36 | + } |
| 37 | + |
| 38 | + for (var i = 0; i < quantity; i++) |
| 39 | + { |
| 40 | + var position = perimeter * (i / quantity); |
| 41 | + var accumulatedPerimeter = 0; |
| 42 | + |
| 43 | + for (var j = 0; j < points.length; j++) |
| 44 | + { |
| 45 | + var pointA = points[j]; |
| 46 | + var pointB = points[(j + 1) % points.length]; |
| 47 | + var line = new Line( |
| 48 | + pointA.x, |
| 49 | + pointA.y, |
| 50 | + pointB.x, |
| 51 | + pointB.y |
| 52 | + ); |
| 53 | + var length = Length(line); |
| 54 | + |
| 55 | + if (position < accumulatedPerimeter || position > accumulatedPerimeter + length) |
| 56 | + { |
| 57 | + accumulatedPerimeter += length; |
| 58 | + continue; |
| 59 | + } |
| 60 | + |
| 61 | + var point = line.getPoint((position - accumulatedPerimeter) / length); |
| 62 | + out.push(point); |
| 63 | + |
| 64 | + break; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return out; |
| 69 | +}; |
| 70 | + |
| 71 | +module.exports = GetPoints; |
0 commit comments