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:
a=N1i=1∑Nvi
where:
a is the alignment force.
N is the number of nearest neighbours.
vi is the velocity of each neighbouring boid.
2. Cohesion
Boids move towards the center of mass of their neighbors:
c=N1i=1∑Npi−pboid
c is the cohesion force.
pi is the position of each neighbouring boid.
pboid is the current boid’s position.
3. Separation
Boids avoid collisions by steering away from close neighbors:
s=i=1∑N∣pboid−pi∣pboid−pi
s is the separation force.
pi is the position of each neighbouring boid.
pboid is the current boid’s position.
4. Predator Avoidance
Boids flee from predators by steering away from those within a fleeRadius:
The final velocity update for a boid is a weighted sum of all these forces:
vboid+=(a+c+s+f+h)⋅dt
Velocities are then capped at a max speed, and positions are updated using:
pboid+=vboid⋅dt
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:
p=N1i=1∑Npi−ppredator
where:
N is the number of prey boids inside the predator’s perception radius.
The simulation was created with Typescript, plotted using Observable Plot and rendered inside this Next.js 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!