xxxxxxxxxx
77
class Vehicle {
constructor(x, y) {
//all the usual stuff
this.position = createVector(x, y);
this.r = 12;
this.maxspeed = 3; //max speed
this.maxforce = 0.2; //max steering force
this.acceleration = createVector(0, 0);
this.velocity = createVector(0, 0);
}
applyForce(force) {
//add mass here if we want A = F / M
this.acceleration.add(force);
}
//separation
//method checks for nearby vehicles and steers away
separate(vehicles) {
let desiredseparation = this.r * 2;
let sum = createVector();
let count = 0;
//for every boid in the system, check if it's too close
for (let i = 0; i < vehicles.length; i++) {
let d = p5.Vector.dist(this.position, vehicles[i].position);
//if the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
if ((d > 0) && (d < desiredseparation)) {
//calculate vector pointing away from neighbor
let diff = p5.Vector.sub(this.position, vehicles[i].position);
diff.normalize();
diff.div(d); //weight by distance
sum.add(diff);
count++; //keep track of how many
}
}
//average: divide by how many
if (count > 0) {
sum.div(count);
//our desired vector is the average scaled to max speed
sum.normalize();
sum.mult(this.maxspeed);
//implement Reynolds: steering = desired - velocity
let steer = p5.Vector.sub(sum, this.velocity);
steer.limit(this.maxforce);
this.applyForce(steer);
}
}
//method to update location
update() {
//update velocity
this.velocity.add(this.acceleration);
//limit speed
this.velocity.limit(this.maxspeed);
this.position.add(this.velocity);
//reset accelertion to 0 each cycle
this.acceleration.mult(0);
}
display() {
fill(63,63,147);
stroke(50);
strokeWeight(2);
push();
translate(this.position.x, this.position.y);
ellipse(0, 0, this.r, this.r);
pop();
}
//wraparound
borders() {
if (this.position.x < -this.r) this.position.x = width + this.r;
if (this.position.y < -this.r) this.position.y = height + this.r;
if (this.position.x > width + this.r) this.position.x = -this.r;
if (this.position.y > height + this.r) this.position.y = -this.r;
}
}