Swarm Behaviour in Fish
This small real time simulation aims to capture some of the emerging dynamics of simple rules. In the boids algoririthm, developed by Craig Reynolds in 1986, rules about alignment, separation, and cohesion cause swarm behaviour. Its the same behaviour observed in birds and schools of fish.
Figure 1: Real time simulation running in your browser.
Boids algorithm which leads to emergent behaviour like flocking/school formation, implemented in this simulation as follows:
1. Alignment
Boids steer towards the average direction of their neighbors within a set perception radius:
where:
is the alignment force. is the number of nearest neighbours. is the velocity of each neighbouring boid.
2. Cohesion
Boids move towards the center of mass of their neighbors:
is the cohesion force. is the position of each neighbouring boid. is the current boids position.
3. Separation
Boids avoid collisions by steering away from close neighbors:
is the separation force. is the position of each neighbouring boid. is the current boids position.
4. Predator Avoidance
Boids flee from predators by steering away from those within a fleeRadius
:
is the avoidance force. is the number of predators within the flee radius. is a set flee strength.
5. Hotzone Attraction
Hotzones emit a Gaussian potential field that attracts boids:
where:
is the number hotzones. similarly for . are the Gaussian spread parameters.
Combined Behavior
The final velocity update for a boid is a weighted sum of all these forces:
Velocities are then capped at a max speed, and positions are updated using:
Wrapping is used to ensure that boids remain within the bounds of the simulation.
Predators
Predators pursue boids based on proximity and separate from other predators. Their pursuit force is similar to cohesion:
where:
is the number of prey boids inside the predators perception radius.
The simulation was created with Typescript, plotted using Observable Plot and rendered inside this Observable Framework Notebook.
This combination of rules creates lifelike, emergent flocking behavior, balancing attraction, repulsion, and external influences. The prey flee the predators and the predators pursue the prey, and the visualisation just looks nice along the way!