xxxxxxxxxx
87
/*
If a boid fly too high or too low, a force is applied to make it go to the average depth
- So that they tend to fly horizontally
There is also a quad tree to minimize the cost distance calculation
*/
let maxForce = 0.1;
let maxSpeed = 5;
let perception = 150;
const flock = []; // Array of boids
let depth = 800; // The Z location of the boid tend to stay between +depth/2 and -depth/2
let gap = 300; // Boids can go further than the edges, this further distance is the gap
let quadTree; // A quad tree to minimize the cost of distance calculation
let unitX, unitY, unitZ; // Unit vectors pointing in the X, Y, and Z directions
let useQuadTree = true; // Toogle the use of a quad tree
let boidsP, perceptionP, alignmentP, cohesionP, separationP; // Paragraphs
let startingBoids = 200; // Amount of boid at the start of the sketch
let startingPerception = 90; // Perception radius at the start of the sketch
// SETUP FUNCTION ---------------------------------------------------
// Make the canvas, declare some variables, create the DOM elements and the initial boid population
function setup() {
// Declaration of a canvas to allow canvas download
let p5Canvas;
p5Canvas = createCanvas(800, 800, WEBGL); // You can change the resolution here
// Declaration of depth (z axis), unit vectors, and the camera
depth = height;
unitX = createVector(1, 0, 0);
unitY = createVector(0, 1, 0);
unitZ = createVector(0, 0, 1);
let cameraX = 630 / 600 * width;
let cameraY = 140 / 500 * height;
let cameraZ = -280 / 500 * depth;
// Create an initial population of 100 boids
for (let i = 0; i < startingBoids; i++) {
pushRandomBoid();
}
}
// DRAW FUNCTION ---------------------------------------------------
function draw() {
orbitControl();
// Background and lightning
background(255);
// Draw the corners of a box showing the space where boids can fly
stroke(80);
strokeWeight(8);
noFill();
box(width + gap/2, height + gap/2, depth + gap/2);
// Make the quad tree
let boundary = new Cube(0, 0, 0, width + 2 * gap, height + 2 * gap, depth + 2 * gap);
quadTree = new QuadTree(boundary, 4);
for (let boid of flock) {
quadTree.insert(boid);
}
// Each boid determines its acceleration for the next frame
for (let boid of flock) {
boid.flock(flock, quadTree);
}
// Each boid updates its position and velocity, and is displayed on screen
for (let boid of flock) {
boid.update(gap);
boid.show();
}
}
// Make a new boid
function pushRandomBoid() {
let pos = createVector(random(width), random(height), random(-depth/2, depth/2)); // Uncomment and comment next line to create boids at random position
let vel = p5.Vector.random3D().mult(random(0.5, 3)); // Give a random velocity
let boid = new Boid(pos, vel); // Create a new boid
flock.push(boid); // Add the new boid to the flock
}