-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboid.js
113 lines (105 loc) · 2.89 KB
/
boid.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
113
class Boid {
constructor() {
this.position = createVector(random(width), random(height));
this.velocity = p5.Vector.random2D();
this.acceleration = createVector();
this.maxForce = 0.2;
this.maxSpeed = 5;
this.velocity.setMag(
random(
random(-this.maxSpeed / 2, this.maxSpeed / 2),
random(-this.maxSpeed / 2, this.maxSpeed / 2)
)
);
}
edges(boundaryType) {
if (boundaryType === 'Unbound') {
if (this.position.x > width) {
this.position.x = 0;
} else if (this.position.x < 0) {
this.position.x = width;
}
if (this.position.y > height) {
this.position.y = 0;
} else if (this.position.y < 0) {
this.position.y = height;
}
} else if (boundaryType === 'Bound') {
if (this.position.x > width || this.position.x < 0) {
this.velocity.x *= -1;
} else if (this.position.y > height || this.position.y < 0) {
this.velocity.y *= -1;
}
}
}
flock(boids) {
let perceptionRadius = perceptSlider.value();
let total = 0;
let toAlign = createVector();
let toGroup = createVector();
let toSeperate = createVector();
for (let other of boids) {
let d = dist(
this.position.x,
this.position.y,
other.position.x,
other.position.y
);
if (other != this && d < perceptionRadius) {
// Alignment
toAlign.add(other.velocity);
// Chohesion
toGroup.add(other.position);
// Separation
let diff = p5.Vector.sub(this.position, other.position);
diff.mult(1 / (d * d));
toSeperate.add(diff);
total++;
}
}
if (total > 0) {
toAlign.div(total);
toAlign.setMag(this.maxSpeed);
toAlign.sub(this.velocity);
toAlign.limit(this.maxForce);
toGroup.div(total);
toGroup.sub(this.position);
toGroup.setMag(this.maxSpeed * 0.75);
toGroup.sub(this.velocity);
toGroup.limit(this.maxForce);
toSeperate.div(total);
toSeperate.setMag(this.maxSpeed);
toSeperate.sub(this.velocity);
toSeperate.limit(this.maxForce);
}
toAlign.mult(alignSlider.value());
toGroup.mult(cohesionSlider.value());
toSeperate.mult(separationSlider.value());
this.acceleration.add(toAlign);
this.acceleration.add(toGroup);
this.acceleration.add(toSeperate);
}
update() {
this.position.add(this.velocity);
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxSpeed);
this.acceleration.set(0, 0);
}
show(percept) {
strokeWeight(2);
stroke(255);
point(this.position.x, this.position.y);
if (percept) {
rectMode(CENTER);
noFill();
strokeWeight(1);
stroke(0, 255, 0);
circle(
this.position.x,
this.position.y,
perceptSlider.value(),
perceptSlider.value()
);
}
}
}