Flocking

I can’t remember where, or when, I first heard about simulating flocking behaviour, but I’ve always loved it because you can generate an effect that is interesting and mesmerising from just a few simple rules. For this simulation, I’ve used Paper.js, an open-source vector graphics library for JavaScript that draws onto an HTML5 Canvas element. I started by creating a number of ‘birds’ with a random position, direction, and a fixed speed. With the application of the three rules the birds can turn left or right or just continue. And that’s basically it.

Here are those three rules courtesy of Wikipedia:

Separation

Avoid crowding neighbours (short range repulsion) (i.e. if you are too close to another bird, then steer away).

Alignment

Steer towards average heading of neighbours.

Cohesion

Steer towards average position of neighbours (long range attraction).

Applying these three rules in that order of priority gives you the fascinating emergent behaviour.

Below is the simulation in action. Click on the cog to bring up some options you can play with. The ‘Contain’ setting refers to whether the birds aim to stay contained within the canvas, or whether they will wrap around to the opposite side when they go out of bounds.

Tip: if you are using a mobile device, it’s best to view in landscape to give the birds enough room to move about, or better still, on a larger desktop machine.

Scroll to Top