Interactive demo
Boids Flocking Simulation
This code is based on the boids idea by Craig Reynolds. For more information visit https://www.red3d.com/cwr/boids/. The flocking behaviour of the boids tries to simulate the natural way fish or birds would move in groups. This simulation only needs three core rules: alignment, cohesion and separation.
Rule weights
Display
The three rules of flocking

Alignment
Steer towards the average heading of local flockmates.

Cohesion
Steer to move toward the average position of local flockmates.

Separation
Steer to avoid crowding local flockmates.
In 3D: a school of fish and a flock of starlings
The same three rules work in three dimensions. Every fish or bird only looks at its neighbors, yet the whole group turns, splits and joins again as one. A few additions make it more lifelike: a field of view, a space to stay in, a preference for level travel and a predator to flee from.
Drag to look around and scroll to zoom. Switch on the shark or the falcon and watch the group burst apart and close up again behind it.
Display
Rule weights
Neighbors
Field of view
A boid only sees neighbors within its view radius and in front of it: fish see about 300° around them, birds 270°. Whatever is directly behind does not count.
Staying together
Near the edges of the water or the sky, a boid steers back inside, and a gentle pull towards level travel keeps the group from drifting up and down. Birds lean into their turns and flap when they climb; fish beat their tails faster when they speed up.
Fleeing
The shark and the falcon chase the nearest boid ahead of them. Every boid close to the hunter steers away more strongly than any other rule allows, so the group bursts apart and closes again behind it.
Seven nearest neighbors
Observations of starling flocks over Rome showed that each bird reacts to about seven nearest neighbors, no matter how near or far they are. Choose “Only the 7 nearest” to try this topological rule instead of a fixed view radius.
Credits
- Craig W. Reynolds: Flocks, Herds, and Schools: A Distributed Behavioral Model (SIGGRAPH 1987), the paper that introduced boids.
- M. Ballerini et al.: Interaction ruling animal collective behavior depends on topological rather than metric distance (PNAS, 2008), the source of the seven nearest neighbors.