xxxxxxxxxx
89
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//sketch NOC_6_02
// The "Vehicle" class
class Vehicle {
constructor(x, y) {
this.img = img;
this.imgHeight = 1.5 * imgSize;
this.imgWidth = 1 * imgSize;
this.acceleration = createVector(0, 0);
this.velocity = createVector(0, -2);
this.position = createVector(x, y);
this.r = 6;
this.maxspeed = 5;
this.maxforce = 5;
this.system = new ParticleSystem();
}
// 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 accelerationelertion to 0 each cycle
this.acceleration.mult(0);
// Should this code be in update?? Probably not.
let gravity = createVector(0, 0.001);
this.system.applyForce(gravity);
this.system.run();
}
addParticle() {
this.system.addParticle(this.position.x, this.position.y);
}
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
arrive(target) {
var desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
var d = desired.mag();
// Scale with arbitrary damping within 100 pixels
if (d < 100) {
var m = map(d, 0, 100, 0, this.maxspeed);
desired.setMag(m);
} else {
desired.setMag(this.maxspeed);
}
// Steering = Desired minus Velocity
var steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce); // Limit to maximum steering force
this.applyForce(steer);
}
display() {
// Draw an image rotated in the direction of velocity
var theta = this.velocity.heading() + PI / 2;
fill(127);
stroke(200);
strokeWeight(1);
push();
imageMode(CENTER);
translate(this.position.x, this.position.y);
rotate(theta);
image(this.img, 0, 0, this.imgHeight, this.imgWidth);
pop();
}
}