Date

Simulating a flock of fish in React

Introduction

This is a simulation that tries to imitate the behaviour of flocks in nature. It works by simulating each boid in the flock individually, and making them react to their surroundings.

A boid

“Boid” is an expression originally made by Craig Reynols. It describes an entity in a flock, like a bird, fish or bee. The most straight forward way to represent these boids in code is propably to make a Boid class or object with properties such as position and velocity.

The 3 rules

To simulate the movement of these boids, we need to make up some rules. In a popular paper about flocks, herds and schools, 3 primary rules are described: alignment, cohesion and separation.

Alignment (aka velocity matching)

The first rule states, that each boid should try to align itself with nearby boids. This can be done by getting the average velocity of all boids within some radius of the boid.

Cohesion (aka flock centering)

The boid should attempt to stay close to nearby flockmates, as in nature getting lost from the flock often results in certain death (i think).

Separation (aka collision avoidance)

The boid should also keep it’s distance to it’s flockmates to avoid collisions.

Fluid movement

Now with all these rules, we know where the boid should move to, but we don’t want it to move there immediately. That’s why we make the boid seek towards it’s goal, instead of snapping to it immediately. This is done by calculating the desired velocity to reach the goal, and setting a max force that limits how quickly, the boid is allowed to move towards that goal.

Code

Below you’ll find a boid simulation written in TypeScript, React and Tailwind CSS.

Ideas for improvements

  • Optimize the simulation by using a quadtree.
  • Create the simulation in 3D. You could draw some inspiration from Sebasian Lague’s video
  • Implement a view triangle instead of radius for the boids. This will propably give more realistic results for the boids movement.
  • Add a predator that other boids will avoid.

References

  1. Flocks, Herds, and Schools: A Distributed Behavioral Model 1 - Craig W. Reynolds
  2. Coding Adventure: Boids - Sebastian Lague
  3. Implementing Boids in JavaScript Canvas - Jumpoff.io