Simulating a Tiny Ecosystem with Boids

I discovered boids a while back and thought they were an incredibly compelling concept. Luckily for me, there are a ton of good resources and implementations of them. For the uninitiated, here is a brief explanation:

“Boids” are a type of flocking simulation that (surprisingly accurately) mimics the behavior of groups of creatures such as birds or schools of fish. The heart of the simulation is three rules that each boid follows:

  1. Separation
  2. Alignment
  3. Cohesion

I’ll leave the details of these out, but they can be found in any of the linked resources. In a nutshell, the three rules represent a constant push and pull between the boids to keep them moving around together without becoming too crowded.

Below is a quick implementation using p5.js, based on this wonderful tutorial by The Coding Train.

I decided to start adding some more rules to add complexity, randomness, and some more semblance of intelligence. I thought it would be interesting to have some more dominant boids and some more timid ones (predator and prey). Below are some of the main rules I added:

  1. Prey flee when a predator is near
  2. Predator boids seek out prey and try to eat them
  3. Predator boids get larger and glow more the more prey they eat
  4. If an area gets too crowded, all the boids suddenly get mad and run away
  5. Boids can ball up and become immune for a little while if a predator is near and hasn’t caught them yet

The simulation suddenly starts to look much more like a tiny ecosystem in a petri dish.

A live demo can be found here.

Leave a comment