-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
MarchingAnts.js
112 lines (94 loc) · 2.98 KB
/
MarchingAnts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* @author Richard Davey <rich@phaser.io>
* @copyright 2013-2024 Phaser Studio Inc.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Perimeter = require('./Perimeter');
var Point = require('../point/Point');
/**
* Returns an array of points from the perimeter of the Rectangle, where each point is spaced out based
* on either the `step` value, or the `quantity`.
*
* @function Phaser.Geom.Rectangle.MarchingAnts
* @since 3.0.0
*
* @generic {Phaser.Geom.Point[]} O - [out,$return]
*
* @param {Phaser.Geom.Rectangle} rect - The Rectangle to get the perimeter points from.
* @param {number} [step] - The distance between each point of the perimeter. Set to `null` if you wish to use the `quantity` parameter instead.
* @param {number} [quantity] - The total number of points to return. The step is then calculated based on the length of the Rectangle, divided by this value.
* @param {(array|Phaser.Geom.Point[])} [out] - An array in which the perimeter points will be stored. If not given, a new array instance is created.
*
* @return {(array|Phaser.Geom.Point[])} An array containing the perimeter points from the Rectangle.
*/
var MarchingAnts = function (rect, step, quantity, out)
{
if (out === undefined) { out = []; }
if (!step && !quantity)
{
// Bail out
return out;
}
// If step is a falsey value (false, null, 0, undefined, etc) then we calculate
// it based on the quantity instead, otherwise we always use the step value
if (!step)
{
step = Perimeter(rect) / quantity;
}
else
{
quantity = Math.round(Perimeter(rect) / step);
}
var x = rect.x;
var y = rect.y;
var face = 0;
// Loop across each face of the rectangle
for (var i = 0; i < quantity; i++)
{
out.push(new Point(x, y));
switch (face)
{
// Top face
case 0:
x += step;
if (x >= rect.right)
{
face = 1;
y += (x - rect.right);
x = rect.right;
}
break;
// Right face
case 1:
y += step;
if (y >= rect.bottom)
{
face = 2;
x -= (y - rect.bottom);
y = rect.bottom;
}
break;
// Bottom face
case 2:
x -= step;
if (x <= rect.left)
{
face = 3;
y -= (rect.left - x);
x = rect.left;
}
break;
// Left face
case 3:
y -= step;
if (y <= rect.top)
{
face = 0;
y = rect.top;
}
break;
}
}
return out;
};
module.exports = MarchingAnts;