xxxxxxxxxx
124
// Arrive
// The Nature of Code
// The Coding Train / Daniel Shiffman
// https://youtu.be/OxHJ-o_bbzs
// https://thecodingtrain.com/learning/nature-of-code/5.4-arrive.html
// https://editor.p5js.org/codingtrain/sketches/1eUnUQnwB
class Vehicle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxSpeed = Infinity;
this.maxForce = 1;
this.r = 16;
}
evade(vehicle) {
let pursuit = this.pursue(vehicle);
pursuit.mult(-1);
return pursuit;
}
pursue(vehicle) {
let target = vehicle.pos.copy();
let prediction = vehicle.vel.copy();
prediction.mult(10);
target.add(prediction);
fill(0, 255, 0);
circle(target.x, target.y, 16);
return this.seek(target);
}
arrive(target) {
var positionNextFrame = p5.Vector.add(this.pos, this.vel);
var displacement = p5.Vector.sub(target, positionNextFrame);
var distance = displacement.mag();
// "ideal" is the square root, but better reaction to a moving
// target can be achieved with a slightly higher number.
// Try setting it slightly below to see why root = 2 is ideal
var root = 2.15;
var desiredSpeed = Math.pow(2 * this.maxForce * distance, 1 / root);
// to avoid tiny oscillations
if (distance < 2)
desiredSpeed = 0.1 * distance;
var force = p5.Vector.sub(displacement.setMag(desiredSpeed), this.vel);
force.limit(this.maxForce);
return force;
}
flee(target) {
return this.seek(target).mult(-1);
}
seek(target) {
let force = p5.Vector.sub(target, this.pos);
var desiredSpeed = this.maxSpeed;
force.setMag(desiredSpeed);
force.sub(this.vel);
force.limit(this.maxForce);
return force;
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.set(0, 0);
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
triangle(-this.r, -this.r / 2, -this.r, this.r / 2, this.r, 0);
pop();
}
edges() {
if (this.pos.x > width + this.r) {
this.pos.x = -this.r;
} else if (this.pos.x < -this.r) {
this.pos.x = width + this.r;
}
if (this.pos.y > height + this.r) {
this.pos.y = -this.r;
} else if (this.pos.y < -this.r) {
this.pos.y = height + this.r;
}
}
}
class Target extends Vehicle {
constructor(x, y) {
super(x, y);
this.vel = p5.Vector.random2D();
this.vel.mult(5);
}
show() {
stroke(255);
strokeWeight(2);
fill("#F063A4");
push();
translate(this.pos.x, this.pos.y);
circle(0, 0, this.r * 2);
pop();
}
}