How to simulate flocking behavior with Boids using HTML5 and Phaser

I bet you don’t know what Boids are.

From Wikipedia: Boids is an artificial life program, developed by Craig Reynolds in 1986, which simulates the flocking behaviour of birds. The name “boid” corresponds to a shortened version of “bird-oid object”, which refers to a bird-like object.

I am going to show you, in a series of posts, how to simulate a flocking behavior and how to use it in other projects which have nothing to do with flocking.

First, a couple of references: you may find interesting the official Boids page by Craig Reynolds, and also the pseudo code by Conrad Parker.

We’ll divide the tutorial step by step, and in the first step we’ll see how to accomplish to the first Boids rule.

Rule 1: Boids try to fly towards the centre of mass of neighbouring boids.

In other words, each boid will try to fly towards the average position of all other boids. It’s quite easy thanks to Phaser Point class and Arcade Physics.

At each frame, boids trajectory is adjusted. Obviously a Boid can’t see all the other boids, but only the ones within a given range.

Look at the example – you may need to reload it if you only see a white ball:

Boids converge to the center of the flock, and if you notice some boids wandering like crazy, that’s because they are too far from any other visible boid.

This is the commented source code:

This was just the beginning as there are two more steps to develop, meanwhile you can download the source code.