Flocking Boids

in #hive-150329last month

No doubt you have seen birds flocking together, creating beautiful shifting patterns as they fly. It is often huge groups of starlings that twist, turn, swoop and swirl across the sky.

If you would like to see a video of these 'murmurations,' I recommend reading Murmuration, one of the greatest shows on earth by @livinguktaiwan. In fact, this post inspired me to write this article.

These patterns can't happen by chance, but what creates them?

Scientists believe that murmurations offer safety in numbers giving protection from predators like peregrine falcons.

The Boids Algorithm

The Boids algorithm was created by Craig Reynolds in 1986 to simulate flocking behaviour.

A boid is a shortened version of 'birdoid' (a bird version of android?), which refers to a bird-like object.

In the Boids algorithm, the complexity of the flocking is generated by the interaction of the boids following a set of rules.

The simplest version of Boids uses three rules which are:

  1. Separation
  2. Alignment
  3. Cohesion

Separation
Each boid steers to avoid crowding local flockmates.

Public Domain

Alignment
Each boid steers toward the average heading of nearby boids.

Public Domain

Cohesion
Each boid steers to move toward the centre of mass of nearby boids.

Public Domain

More complex rules, such as obstacle avoidance and goal seeking, can be added.

A Boids Simulation

I wanted to create a Boids simulation using Python, but unfortunately, this is outside the scope of my current programming skills.

The simulation shown below is a modified Python implementation by OpenAI's ChatGPT.

You can download a copy of this script from the Learning Pages Digital Shop. It is free to use for personal and educational use.

The program uses Pygame to simulate Boids. If you don’t have Pygame, you can install it via pip:

pip install pygame

The flock function combines the three rules to simulate flocking behaviour, adjusting the weights to achieve a balance. You should see the boids grouping and moving as a unit across the screen.

You can modify this program to make it more realistic.

For example:

  • I doubled the number of boids by changing line 14 to:
    num_boids = 100
  • I made 'Sky Blue' the new black by changing line 21 to:
    black = (135, 206, 235)
  • I made 'Mahogany' the new white by changing line 22 to:
    white = (150, 105, 25)

The result of these changes is shown in the video below:

Sort:  

Wow interesting stuff.