-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcyclobots.js
106 lines (91 loc) · 2.93 KB
/
cyclobots.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
var TWO_PI = Math.PI * 2;
var RADIANS_PER_DEGREE = TWO_PI / 360;
Cyclobot = function() {
this.init = function(config) {
this.x = config.x;
this.y = config.y;
this.theta = config.theta; // radians
this.speed = config.speed;
this.dexterity = config.dexterity; // radians
this.next = config.next;
return this;
};
this.move = function() {
var dx = this.speed * Math.cos(this.theta);
var dy = this.speed * Math.sin(this.theta);
this.x += dx;
this.y += dy;
};
this.adjust = function() {
var rho = Math.atan2(this.y - this.next.y, this.x - this.next.x) + Math.PI;
this.rho_deg = Math.floor(rho / RADIANS_PER_DEGREE);
this.theta_deg = Math.floor(this.theta / RADIANS_PER_DEGREE);
// stolen from http://prog21.dadgum.com/96.html
var angle_diff = (this.rho_deg - this.theta_deg + 540) % 360 - 180;
if (angle_diff < 0) {
this.theta -= this.dexterity;
} else {
this.theta += this.dexterity;
}
if (this.theta <= 0) this.theta += TWO_PI;
if (this.theta > TWO_PI) this.theta -= TWO_PI;
};
};
Cyclobots = function() {
var selected = undefined;
var numbots = 50;
var drawAngles = false;
var dragging;
var lastX = undefined;
var lastY = undefined;
this.init = function(config) {
this.bots = [];
this.numbots = 50;
this.onUpdateBot = config.onUpdateBot;
for (var i = 0; i < this.numbots; i++) {
var bot = (new Cyclobot()).init({
x: 50 + Math.random() * (config.width - 100),
y: 50 + Math.random() * (config.height - 100),
theta: Math.random() * TWO_PI,
speed: 2,
dexterity: 2 * RADIANS_PER_DEGREE
});
this.bots.push(bot);
}
this.linkUpBots();
return this;
};
this.forEachBot = function(callback) {
for (var i = 0; i < this.bots.length; i++) {
callback(this.bots[i]);
}
};
this.linkUpBots = function() {
var numBots = this.bots.length;
for (var i = 0; i < numBots - 1; i++) {
this.bots[i].next = this.bots[i + 1];
}
this.bots[numBots - 1].next = this.bots[0];
};
this.update = function() {
var $this = this;
this.forEachBot(function(bot) {
bot.move();
bot.adjust();
if ($this.onUpdateBot) $this.onUpdateBot(bot);
});
};
this.massConfusion = function() {
this.forEachBot(function(bot) {
bot.theta = Math.random() * TWO_PI;
});
};
this.shuffle = function() {
var newBots = [];
while (this.bots.length > 0) {
newBots.push(this.bots.splice(Math.random() * this.bots.length, 1)[0]);
}
this.bots = newBots;
this.linkUpBots();
};
};