Boids

I've always been fascinated by emergent behaviour, there's something cool about simple rules resulting in a complex outcome. I think that Boids is a really good way of demonstrating emergent behaviour.

Boids is an artificial life program, developed by Craig Reynolds in 1986, which simulates the flocking behaviour of birds.

I decided to put together a 2D version of Boids using HTML5 canvas. Click the "Start" link below to see them start moving.

StartStopReset

The boids above follow three very simple rules (that you can switch on and off):

(This isn't a rule, it just helps visualise who's a neighbour!)

What's going on here

I start by creating 30 boids, each with a random starting position and direction.

On each frame, each boid investigates its neighbours and figures out the average directions of those that are reasonably close (within 100px) and those that are too close (within 30px).

If the first rule is enabled then the boid will rotate itself slightly towards the average direction of the reasonably close boids.

If the second rule is enabled then it will rotate itself slightly away from the average direction of the very close boids.

If the third rule is enabled then it will also survey all the boids on the canvas, figure out where the highest population of boids is and rotate slightly in that direction. This is useful for the boids that occasionally disappear off on their own and would otherwise fly off in a straight line forever (which isn't a huge problem in this example, since boids reaching the edge will wrap around to the opposite edge).

It's quite fun disabling the 2nd rule, watching the boids squish up close to each other, and then enabling it again to see them all fly away from each other.

Source code

The source code is available on my github page. It's written in coffeescript and is hopefully fairly self explanatory. I tried making some docco docs but that didn't go very well. Hopefully I'll get them up soon.

Let me know if you have any questions or suggestions @baxt3r

Update

There was a bug in the way that I was rotating boids, check out An angle bug for more information.