xxxxxxxxxx
65
class Vehicle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
this.r = 6;
this.maxspeed = 2;
this.maxforce = 2;
}
// 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 acceleration to 0 each cycle, at each moment of time I'm evaluating the forces acting on me
this.acceleration.mult(0);
}
applyForce(force) {
// We could add mass here if we want A = F / M
this.acceleration.add(force);
}
// A method that calculates a steering force towards a target
// STEER = DESIRED MINUS VELOCITY
seek(target) {
let desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
// Scale to maximum speed
desired.setMag(this.maxspeed);
desired.mult(-1);
// Steering = Desired minus velocity
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce); // Limit to maximum steering force
this.applyForce(steer);
}
show() {
//Vehicle is a triangle pointing in the direction of velocity
let angle = this.velocity.heading();
fill(127);
stroke(0);
push();
translate(this.position.x, this.position.y);
rotate(angle);
beginShape();
vertex(this.r * 2, 0);
vertex(-this.r * 2, -this.r);
vertex(-this.r * 2, this.r);
endShape(CLOSE);
pop();
}
}