-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle.js
72 lines (63 loc) · 1.51 KB
/
vehicle.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
class Vehicle {
constructor(x, y, color = 'red') {
let xChoice = (random(2) >= 1) ? 0 : width;
this.pos = createVector(xChoice, random(height));
this.target = createVector(x, y);
this.vel = p5.Vector.random2D();
this.acc = createVector();
this.r = 5;
this.maxSpeed = 10;
this.maxForce = .5;
this.color = color;
}
behaviors() {
var arrive = this.arrive(this.target);
var mouse = createVector(mouseX, mouseY);
var flee = this.flee(mouse);
arrive.mult(1);
flee.mult(5);
this.applyForce(arrive);
this.applyForce(flee);
}
applyForce(f) {
this.acc.add(f);
}
update() {
this.pos.add(this.vel);
this.vel.add(this.acc);
this.acc.mult(0);
}
show() {
push();
colorMode(RGB);
stroke(this.color);
strokeWeight(this.r);
point(this.pos.x, this.pos.y);
pop();
}
arrive(target) {
var desired = p5.Vector.sub(target, this.pos);
var d = desired.mag();
var speed = this.maxSpeed;
if (d < 100) {
speed = map(d, 0, 100, 0, this.maxSpeed);
}
desired.setMag(speed);
var steer = p5.Vector.sub(desired, this.vel);
steer.limit(this.maxForce);
return steer;
}
flee(target) {
var desired = p5.Vector.sub(target, this.pos);
var d = desired.mag();
if (d < 50) {
desired.setMag(this.maxSpeed);
desired.mult(-1);
var steer = p5.Vector.sub(desired, this.vel);
steer.limit(this.maxForce);
return steer;
} else {
return createVector(0, 0);
}
}
}