xxxxxxxxxx
80
let vehicles = [];
function setup() {
createCanvas(600, 400);
// Create vehicles
for (let i = 0; i < 50; i++) {
let x = random(width);
let y = random(height);
vehicles.push(new Vehicle(x, y));
}
}
function draw() {
background(51);
// Get the mouse position
let target = createVector(mouseX, mouseY);
// Update and display vehicles
for (let vehicle of vehicles) {
vehicle.wander();
// Flee from the mouse
vehicle.flee(target);
vehicle.update();
vehicle.display();
}
}
class Vehicle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(2, 0);
this.acceleration = createVector(0, 0);
this.maxSpeed = 5;
this.maxForce = 0.1;
this.radius = 8;
}
update() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxSpeed);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
applyForce(force) {
this.acceleration.add(force);
}
wander() {
let wanderForce = createVector(random(-1, 1), random(-1, 1));
wanderForce.setMag(this.maxForce);
this.applyForce(wanderForce);
}
flee(target) {
let desired = p5.Vector.sub(target, this.position);
let d = desired.mag();
if (d < 50) {
// Flee only if the target is within a certain radius
desired.setMag(this.maxSpeed);
desired.mult(-1);
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxForce);
this.applyForce(steer);
}
}
display() {
fill(127);
stroke(200);
strokeWeight(2);
ellipse(this.position.x, this.position.y, this.radius * 2, this.radius * 2);
}
}