xxxxxxxxxx
90
var v;
function setup() {
createCanvas(400, 400);
background(255);
v = new Vehicle(200, 0);
}
function draw() {
background(255);
var mouse = createVector(mouseX, mouseY);
fill(200);
stroke(0);
strokeWeight(2);
ellipse(mouse.x, mouse.y, 48, 48);
// v.seek(mouse);
v.update();
v.display();
}
class Vehicle {
constructor(x, y) {
this.location = createVector(x, y);
this.velocity = createVector(-0.6, 0.5);
this.acceleration = createVector(0, 0);
this.r = 3.0;
this.maxforce = 0.1;
this.maxspeed = 4;
}
update() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.location.add(this.velocity);
this.acceleration.mult(0);
if (location.x < 25) {
var desired = createVector(this.maxspeed, this.velocity.y);
var steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce);
this.applyForce(steer);
}
}
applyForce(force) {
this.acceleration.add(force);
}
seek(target) {
var desired = p5.Vector.sub(target, this.location);
var d = desired.mag();
desired.normalize();
if (d < 100) {
var m = map(d, 0, 100, 0, this.maxspeed);
desired.mult(m);
} else {
desired.mult(this.maxspeed);
}
var steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce);
this.applyForce(steer);
}
display() {
var theta = this.velocity.heading() + PI / 2;
fill(175);
stroke(0);
push();
translate(this.location.x, this.location.y);
rotate(theta);
beginShape();
vertex(0, -this.r * 2);
vertex(-this.r, this.r * 2);
vertex(this.r, this.r * 2);
endShape(CLOSE);
pop();
}
}