Flocking simulation

For a long time I wanted to build a flocking simulation. A few years back, I tried to build one using clojurescript and quil, but I wasn't able to get satisfactory performance, so in my second attempt I went with pure javascript and the PIXI library

There is this interesing model called Boids. In a nutshell, you define a set of simple actors (boids) without centralized coordination and a group behavoir emerges, resembling a flock of birds or a school fish.

Each boid has only a limited vision around itself, and makes decision about its speed and direcation based on what other boids are doing in that vision radius.

The principles guiding each boid's behavoir are:

  1. Separation - boid steers await from dense clumps of flockmates
  2. Alignment - boid steers in such a way that its going the same way as its near flockmates
  3. Cohesion - boid steers towards the centre of mass of his near flockmates

These rules are all applied simulaneously, and obviously there are conflicts built into them (eg. separation vs cohesion), which are resolved by careful choice of weighing factor on each steering impulse.

I find the result totally fascinating. From such simple rules, with only a very limited local scope, something greater emerges. It appears to be coordinated somehow, it seems to be organic.

Demo

In my own implementation, I added three additional rules:

  1. Boids steer away from the center of the frame
  2. Boids steer away from the mouse cursor
  3. There is a randomly selected zone in the frame which scares the boids away - this serves to break up large formations of boids which tend to emerge after a while as the simulation stabilizes

The iframe on this page is a bit cramped and it doesn't do justice to the flock. I recommed playing around with the fullscreen version on flock.msladecek.com.

You can find the source code here, although if you search around you will find many other implementations which you'll be able to tweek and play around with it in other ways.