xxxxxxxxxx
123
class Vehicle {
constructor(x, y) {
this.show_details = false
this.show_path = true
this.pos = createVector(x, y);
this.vel = createVector(1, 0);
this.acc = createVector(0, 0);
this.maxSpeed = 4;
this.maxForce = 0.2;
// The happy (5, 12, 13) pythag triple
this.shape = [-12, 5, -12, -5, 13, 0]
this.wanderTheta = PI / 2;
this.currentPath = [];
this.paths = [this.currentPath];
}
wander() {
let wanderPoint = this.vel.copy();
wanderPoint.setMag(100);
wanderPoint.add(this.pos);
if(this.show_details) {
fill(255, 0, 0);
noStroke();
circle(wanderPoint.x, wanderPoint.y, 8);
}
let wanderRadius = 50;
if(this.show_details) {
noFill();
stroke(255);
circle(wanderPoint.x, wanderPoint.y, wanderRadius * 2);
line(this.pos.x, this.pos.y, wanderPoint.x, wanderPoint.y);
}
let theta = this.wanderTheta + this.vel.heading();
let x = wanderRadius * cos(theta);
let y = wanderRadius * sin(theta);
wanderPoint.add(x, y);
if(this.show_details) {
fill(0, 255, 0);
noStroke();
circle(wanderPoint.x, wanderPoint.y, 16);
stroke(255);
line(this.pos.x, this.pos.y, wanderPoint.x, wanderPoint.y);
}
let steer = wanderPoint.sub(this.pos);
steer.setMag(this.maxForce);
this.applyForce(steer);
let displaceRange = 0.3;
this.wanderTheta += random(-displaceRange, displaceRange);
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.set(0, 0);
this.currentPath.push(this.pos.copy());
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
triangle(this.shape);
pop();
if(this.show_path) {
for (let path of this.paths) {
beginShape();
noFill();
for (let v of path) {
vertex(v.x, v.y);
}
endShape();
}
}
}
edges() {
let hitEdge = false;
let extra = 20
if (this.pos.x > width + extra) {
this.pos.x = -extra;
hitEdge = true;
} else if (this.pos.x < -extra) {
this.pos.x = width + extra;
hitEdge = true;
}
if (this.pos.y > height + extra) {
this.pos.y = -extra;
hitEdge = true;
} else if (this.pos.y < -extra) {
this.pos.y = height + extra;
hitEdge = true;
}
if (hitEdge) {
this.currentPath = [];
this.paths.push(this.currentPath);
}
}
}