xxxxxxxxxx
126
class Vehicle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
this.r = 2;
this.maxspeed = 0.5;
this.maxforce = 0.1;
}
seek(target) {
let desired = p5.Vector.sub(target.position, this.position);
desired.setMag(this.maxspeed);
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
}
flee(target) {
return this.seek(target).mult(-1);
}
applyForce(force) {
this.acceleration.add(force);
}
update() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
show() {
let angle = this.velocity.heading();
fill(127);
stroke(0);
push();
translate(this.position.x, this.position.y);
rotate(angle);
beginShape();
triangle(-this.r, -this.r / 2, -this.r, this.r / 2, this.r, 0);
endShape(CLOSE);
pop();
}
edges() {
if (this.position.x > width + this.r) {
this.position.x = -this.r;
} else if (this.position.x < -this.r) {
this.position.x = width + this.r;
}
if (this.position.y > height + this.r) {
this.position.y = -this.r;
} else if (this.position.y < -this.r) {
this.position.y = height + this.r;
}
}
}
//creating a new class for the moving target that inherents from the parent class Vehicle
class Target extends Vehicle {
constructor(x, y) {
super(x, y); //calls the parent's constructor
this.velocity = createVector(1,0); //gives it a random direction - normalized
// this.velocity.mult(5);
this.acceleration = createVector(0, 0);
this.r = 2;
this.maxspeed = 0.5;
this.maxforce = 0.2;
this.wanderTheta = 0;
}
wander() {
// creating projected wandering point
let wanderPoint = this.velocity.copy();
wanderPoint.setMag(100);
wanderPoint.add(this.position);
//displaying wandering point
fill(255, 0, 0);
noStroke();
// circle(wanderPoint.x, wanderPoint.y, 8);
//creating a circular path around my wandering point
let wanderRadius = 3;
noFill();
stroke(0);
// circle(wanderPoint.x, wanderPoint.y, wanderRadius * 2);
// line(this.position.x, this.position.y, wanderPoint.x, wanderPoint.y);
//the angle is relevant to the direction the vehicle's current velocity
let theta = this.wanderTheta + this.velocity.heading();
//finding the point on the circumference of the circular path, remember polar to cartesian coordinates
let x = wanderRadius * cos(theta);
let y = wanderRadius * sin(theta);
wanderPoint.add(x, y);
//displaying new wandering point on circular path and line to it
// fill(0, 255, 0);
// noStroke();
// circle(wanderPoint.x, wanderPoint.y, 10);
// stroke(0);
// line(this.position.x, this.position.y, wanderPoint.x, wanderPoint.y);
//the steering force here is equivalent to the desired velocity = target-position
let steer = wanderPoint.sub(this.position);
steer.setMag(this.maxForce);
this.applyForce(steer);
//random displacement along the circumference
let displaceRange = 0.3;
this.wanderTheta += random(-displaceRange, displaceRange);
}
}