-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
65 lines (53 loc) · 1.35 KB
/
main.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
const canvas = document.getElementById("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
const ctx = canvas.getContext("2d")
function flock() {
for (let boid of boids) {
separation(boid, boids);
alignment(boid, boids);
cohesion(boid, boids);
}
}
function handleTurns(dot) {
if (dot.position.x > WIDTH) {
dot.velocity.x -= PARAMETERS.TURN_FACTOR;
}
if (dot.position.x < 0) {
dot.velocity.x += PARAMETERS.TURN_FACTOR;
}
if (dot.position.y > HEIGHT) {
dot.velocity.y -= PARAMETERS.TURN_FACTOR;
}
if (dot.position.y < 0) {
dot.velocity.y += PARAMETERS.TURN_FACTOR;
}
}
function update() {
for (let boid of boids) {
boid.velocity = Vectors.limit(boid.velocity, PARAMETERS.MAX_VELOCITY);
boid.position = Vectors.add(boid.position, boid.velocity);
handleTurns(boid);
}
}
function drawDot({ x, y }) {
ctx.beginPath();
ctx.arc(x, y, 5, 2 * Math.PI, 0);
ctx.fillStyle = 'white';
ctx.fill();
}
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
for (let boid of boids) {
drawDot(boid.position)
}
}
function loop(time) {
flock();
update();
draw();
window.requestAnimationFrame(loop);
}
window.requestAnimationFrame(loop);