Boids

Oct 14, 2024·
Edwin Laverde-Villarreal
Edwin Laverde-Villarreal
· 2 min read
Animation of the obtained boids, periodic walls

What are boids?

Flocks of birds, schools of fish, swarms of bees, they all represent a bunch of individual entities that by themselves may not exhibit complex behaviours, but when seen in a group they exhibit a collective complex emergent movement that is really interesting.

A way to model these swarms is with the boids algorithm devised by Craig Reynolds in 1986. The boids algorithm establishes a set of 3 rules that the swarm entities follow:

  • Separation: Each boid steers away from local boids so as to avoid crowding (and possible accidents).
  • Alignment: Each boid tries to align its velocity (speed and direction) to that of the neighbouring boids.
  • Cohesion: Each boid tries to move to the average position of the neighbouring boids (center of mass).

Implementation

The animation showed above is my implementation of these rules in python, and the code can be found here. Along with the rules, I also implemented a grid algorithm to reduce the order of the computations (from checking all boids, to just checking those in near cells).

I also implemented the boids alogrithm using Javascript’s p5 library. This implementation is pretty similar to the one in python, but certainly easier to play around with. And this one also includes the possibility for the user to act as a predator (when clicking the mouse), which causes nearby boids to get scared, turn red, and run away from you. You can try it out here. Press the play button and see how the boids boid away! You can also tweak some of the parameters at the top of the code to see how it affects the behaviour.

Coming soon
Want to put the p5 implementation here by itself too

Resources