Getting To Grips With Flocking

by Sam Fereday

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.15/p5.min.js"></script>

JavaScript

var boids = [];
var _obsticle;

function setup() {
  createCanvas(512, 512);

  // Add an initial set of boids into the system
  for (var i = 0; i < 100; i++) {
    boids[i] = new Boid(random(width), random(height));
  }
  //_obsticle = new Obsticle(boids);
}

function draw() {
  background(51);
  //_obsticle.render();
  // Run all the boids
  for (var i = 0; i < boids.length; i++) {
    boids[i].run(boids);
  }
}

// An obsticle to be avoided
function Obsticle(flock){
  this._flock = flock;
  this.rad = 30;
  this.xpos = 200;
  this.ypos = 200;
  this.repulsion = 80;
  this.attractiveness = -100;
  this.position = createVector(this.xpos, this.ypos)
  this.colour = {r:255,g:0, b:255};
}

Obsticle.prototype.update = function(){
  for( var i=0; i<this._flock.length; i++){
    var f = this._flock[i];
    var vec = createVector(f.position.x, f.position.y);
    var exclusion = createVector(this.position.x,this.position.y);
    vec.sub(exclusion);
    if(vec.mag() < this.repulsion ){
        stroke(255, 0,0);
        //line(this.position.x, this.position.y, f.position.x, f.position.y);
        //stroke(100, 255,0)
        //line(this.position.x, this.position.y, exclusion.x, exclusion.y);
      this._flock[i].applyForce(vec.mult(100));
    }
  }
}

Obsticle.prototype.render = function(){
  this.update();
  fill(this.colour.r, this.colour.g, this.colour.b);
  ellipse(this.xpos, this.ypos, this.rad, this.rad);
}

// Boid class
// Methods for Separation, Cohesion, Alignment added
function Boid(x, y) {
  this._bounceBorders = true;
  this.acceleration = createVector(0, 0);
  this.velocity = p5.Vector.random2D();
  this.position = createVector(x, y);
  this.r = 3.0;
  this.maxspeed = 3;    // Maximum speed
  this.maxforce = 0.15; // Maximum steering force
}

Boid.prototype.run = function(boids) {
  this.flock(boids);
  this.update();
  this.borders();
  this.render();
}

// Forces go into acceleration
Boid.prototype.applyForce = function(force) {
 ...