xxxxxxxxxx
76
var boids = [];
function setup() {
createCanvas(640, 480);
initBoids(100);
}
function draw() {
background(225);
drawBoids();
moveBoids();
}
class Boid {
constructor() {
this.id = Date.now();
this.position = createVector(width/2, height/2);
this.velocity = createVector(random(-5, 5), random(-5, 5));
}
update(velocity = 0) {
this.velocity = this.velocity.add(velocity);
this.position = this.position.add(this.velocity);
}
render() {
push();
translate(this.position.x, this.position.y);
rotate(this.velocity.heading());
stroke(0);
fill(255);
triangle(10, 0, -5, -5, -5, 5);
pop();
}
equals(boid) {
return boid.id === this.id;
}
}
function initBoids(number) {
for (var n = 0; n < number; n++) {
boids[n] = new Boid();
}
}
function drawBoids() {
boids.forEach(boid => boid.render());
}
function moveBoids() {
for (var n = 0; n < boids.length; n++) {
var boid = boids[n];
boid.update(bounding(boid));
// boid.update(cohesion(boid));
}
}
function bounding(boid) {
if (boid.position.x < 0) boid.position.x = 10;
else if (boid.position.x > width) boid.position.x = -10;
if (boid.position.y < 0) boid.position.y = 10;
else if (boid.position.y > height) boid.position.y = -10;
}
function cohesion(boid) {
var velocity = createVector(0, 0);
for (var n = 0; n < boids.length; n++) {
var b = boids[n];
if (!b.equals(boid)) velocity.add(b.position);
}
velocity = velocity.div(boids.length - 1);
return velocity.div(100);
}