xxxxxxxxxx
120
class Boid{
constructor(){
this.position = createVector(random(-sizeX/2,sizeX/2), random(-sizeY/2, sizeY/2), random(-sizeZ/2,sizeZ/2));
this.velocity = p5.Vector.random3D();
this.velocity.setMag(random(2,4));
this.acceleration = createVector();
this.maxForce = 0.02;
this.maxSpeed = 2;
this.coloring = p5.Vector.random3D().setMag(255);
this.sizing = random(100,500);
}
align(boids){
let perceptionRadius = 20;
let steering = createVector();
let total = 0;
for(let other of boids){
let d = dist(this.position.x, this.position.y, this.position.z, other.position.x, other.position.y,other.position.z);
if(other != this && d < perceptionRadius){
steering.add(other.velocity);
total++;
}
}
if(total > 0){
steering.div(total);
steering.setMag(this.maxSpeed);
steering.sub(this.velocity);
steering.limit(this.maxForce);
}
return steering;
}
cohesion(boids){
let perceptionRadius = 100;
let steering = createVector();
let total = 0;
for(let other of boids){
let d = dist(this.position.x, this.position.y, this.position.z, other.position.x, other.position.y,other.position.z);
if(other != this && d < perceptionRadius){
steering.add(other.position);
total++;
}
}
if(total > 0){
steering.div(total);
steering.sub(this.position);
steering.setMag(this.maxSpeed);
steering.sub(this.velocity);
steering.limit(this.maxForce);
}
return steering;
}
separation(boids){
let perceptionRadius = 20;
let steering = createVector();
let total = 0;
for(let other of boids){
let d = dist(this.position.x, this.position.y, this.position.z, other.position.x, other.position.y,other.position.z);
if(other != this && d < perceptionRadius){
let diff = p5.Vector.sub(this.position, other.position);
diff.div(d);
steering.add(diff);
total++;
}
}
if(total > 0){
steering.div(total);
steering.setMag(this.maxSpeed);
steering.sub(this.velocity);
steering.limit(this.maxForce);
}
return steering;
}
flock(boids){
let alignment = this.align(boids);
let cohesion = this.cohesion(boids);
let separation = this.separation(boids);
alignment.mult(alignSlider.value());
cohesion.mult(cohesionSlider.value());
separation.mult(separationSlider.value());
this.acceleration.add(alignment);
this.acceleration.add(cohesion);
this.acceleration.add(separation);
}
update(){
this.position.add(this.velocity);
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxSpeed);
this.acceleration.mult(0);
}
border(){
if(this.position.x > sizeX/2) this.position.x = -sizeX/2;
if(this.position.x < -sizeX/2) this.position.x = sizeX/2;
if(this.position.y > sizeY/2) this.position.y = -sizeY/2;
if(this.position.y < -sizeY/2) this.position.y = sizeY/2;
if(this.position.z > sizeZ/2) this.position.z = -sizeZ/2;
if(this.position.z < -sizeZ/2) this.position.z = sizeZ/2;
}
show(){
strokeWeight(this.sizing);
stroke(this.coloring.x, this.coloring.y, this.coloring.z,200);
point(this.position.x, this.position.y, this.position.z);
}
}