-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle.js
73 lines (62 loc) · 1.69 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
73
// Daniel Shiffman
// http://codingtra.in
// Steering Text Paths
// Video: https://www.youtube.com/watch?v=4hA7G3gup-4
function Vehicle(x, y) {
this.pos = createVector(random(width), random(height));
this.target = createVector(x, y);
this.vel = p5.Vector.random2D();
this.acc = createVector();
this.r = 8;
this.maxspeed = 10;
this.maxforce = 1;
this.color = 255;
}
Vehicle.prototype.behaviors = function() {
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);
}
Vehicle.prototype.applyForce = function(f) {
this.acc.add(f);
}
Vehicle.prototype.update = function() {
this.pos.add(this.vel);
this.vel.add(this.acc);
this.acc.mult(0);
}
Vehicle.prototype.show = function() {
stroke(this.color,100, 100);
strokeWeight(this.r);
point(this.pos.x, this.pos.y);
}
Vehicle.prototype.arrive = function(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;
}
Vehicle.prototype.flee = function(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);
}
}