xxxxxxxxxx
82
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
// Path Following
// Path is a just a straight line in this example
// Via Reynolds: // http://www.red3d.com/cwr/steer/PathFollow.html
// Using this variable to decide whether to draw all the stuff
let debug = false;
// A path object (series of connected points)
let path;
// Two vehicles
let vehicles = [];
function setup() {
createCanvas(640, 360);
newPath();
// Each vehicle has different maxspeed and maxforce for demo purposes
for (let i = 0; i < 120; i++) {
newVehicle(random(width),random(height));
}
}
function draw() {
background(51);
// Display the path
path.display();
vehicles.forEach( v => {
// The boids follow the path
v.follow(path);
v.separate(vehicles);
// Call the generic run method (update, borders, display, etc.)
v.run();
// Check if it gets to the end of the path since it's not a loop
v.borders(path);
});
// Instructions
fill(0);
textAlign(CENTER);
text("Hit 'd' to toggle debugging lines.\nClick the mouse to generate new vehicles.",width/2,height-20);
}
function newPath() {
// A path is a series of connected points
// A more sophisticated path might be a curve
path = new Path();
let offset = 30;
path.addPoint(offset,offset);
path.addPoint(width-offset,offset);
path.addPoint(width-offset,height-offset);
path.addPoint(width/2,height-offset*3);
path.addPoint(offset,height-offset);
}
function newVehicle(x, y) {
let maxspeed = random(2,4);
let maxforce = 0.3;
vehicles.push(new Vehicle(x,y,maxspeed,maxforce));
}
function keyPressed() {
if (key == 'D') {
debug = !debug;
}
}
function mousePressed() {
newVehicle(mouseX, mouseY);
}