xxxxxxxxxx
122
class Vehicle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
this.r = 10;
this.maxspeed = 1;
this.maxforce = 0.5;
}
wander() {
let angle = noise(this.xoff) * TWO_PI * 2;
let steer = p5.Vector.fromAngle(angle);
steer.setMag(this.maxForce);
this.applyForce(steer);
this.xoff += 0.01;
}
//The pursue method is figuring out the predicted future position and calling the seek() method
pursue(vehicle) {
let target = vehicle.position.copy();
let prediction = vehicle.velocity.copy();
prediction.mult(10); //looking 10 steps ahead
target.add(prediction);
fill(0, 255, 0);
//circle(target.x, target.y, 10); //to visualise the prediction
return this.seek(target);
}
seek(target) {
let desired = p5.Vector.sub(target, this.position);
desired.setMag(this.maxspeed);
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce);
return steer;
}
evade(vehicle) {
let pursuit = this.pursue(vehicle);
pursuit.mult(-1);
return pursuit;
}
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 + HALF_PI);
image(boat, -50, -50, 100, 100);
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 = p5.Vector.random2D(); //gives it a random direction - normalized
this.velocity.mult(5);
}
show() {
let angle = this.velocity.heading();
fill(127);
stroke(0);
push();
translate(this.position.x, this.position.y);
rotate(angle + HALF_PI); // Subtract HALF_PI to adjust the rotation by 90 degrees
image(fishies, -50, -50,50, 50); // Display the image with the tip at the center
pop();
}
}
class Target2 extends Vehicle {
constructor(x, y) {
super(x, y); //calls the parent's constructor
this.velocity = p5.Vector.random2D(); //gives it a random direction - normalized
this.velocity.mult(5);
}
show() {
let angle = this.velocity.heading();
fill(127);
stroke(0);
push();
translate(this.position.x, this.position.y);
rotate(angle + HALF_PI);
image(shark, -50, -50,80, 120);
pop();
}
}