-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (81 loc) · 2.01 KB
/
index.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
import p5 from "p5";
import { Boid } from "./boid";
import { Predator } from "./predator";
import { Vector } from "./vector";
import { createSlider, createCheckbox, createNumberInput } from "./hud";
window.onload = () => {
let predators;
let flock;
const align = createSlider({
min: 0,
max: 5,
defaultValue: 1,
step: 0.1,
label: "align",
});
const cohesion = createSlider({
min: 0,
max: 5,
defaultValue: 1,
step: 0.1,
label: "cohesion",
});
const separation = createSlider({
min: 0,
max: 5,
defaultValue: 1,
step: 0.1,
label: "separation",
});
const repelCursor = createCheckbox({
label: "repel cursor",
defaultValue: true,
});
const numOfPredators = createNumberInput({
label: "predators",
defaultValue: 1,
min: 0,
max: 10,
});
const state = () => ({
alignMultiplier: align.value(),
cohesionMultiplier: cohesion.value(),
separationMultiplier: separation.value(),
repelCursor: repelCursor.value(),
});
const sketch = (s) => {
s.setup = () => {
s.createCanvas(800, 600);
Object.assign(s, { state });
flock = Boid.createFlock(100, s);
predators = Predator.createFlock(numOfPredators.value(), s);
numOfPredators.onInput((e) => {
const next = Number(e.target.value);
if (next > predators.length) {
predators.push(new Predator(s));
} else if (next < predators.length) {
predators.pop();
}
});
};
s.draw = () => {
s.background(242, 236, 216);
flock.forEach((boid) => {
boid.flock(flock);
boid.repel(
[]
.concat(predators.map((p) => p.position))
.concat(state().repelCursor ? [Vector(s.mouseX, s.mouseY)] : [])
);
boid.update();
Boid.render(boid, s);
});
predators.forEach((predator) => {
predator.update();
predator.flock(flock);
Predator.render(predator, s);
});
};
};
new p5(sketch);
};