A real-time flocking simulation in C using Raylib, implementing Craig Reynolds' Boids algorithm (1987).
Boids simulates emergent flocking behaviour like the kind seen in starling murmurations using three simple local rules applied to each agent every frame.
Each boid looks at its neighbours within NEIGHBOUR_RADIUS and applies:
| Rule | Description |
|---|---|
| Separation | Steer away from neighbours that are too close, weighted by inverse distance |
| Alignment | Steer toward the average velocity (heading) of local neighbours |
| Cohesion | Steer toward the average position (centre of mass) of local neighbours |
The separation force uses inverse-distance weighting so closer neighbours push harder:
push = normalize(my_pos - neighbor_pos) * (1 / distance)
All three forces are combined and applied to velocity each frame, then clamped between MIN_SPEED and MAX_SPEED to keep boids moving at all times.
Dependencies:
# Ubuntu/Debian
sudo apt install libraylib-devCompile:
gcc main.c -o boids -lraylib -lmRun:
./boidsAll tunable constants are defined at the top of main.c:
| Constant | Default | Effect |
|---|---|---|
NUM_BOIDS |
250 | Number of agents |
NEIGHBOUR_RADIUS |
200.0 | Perception radius in pixels |
MAX_SPEED |
500.0 | Maximum velocity (px/s) |
MIN_SPEED |
300.0 | Minimum velocity which prevents boids from stopping |
TRIANGLE_SIZE |
15.0 | Visual size of each boid |
- Euler integration — velocity updated from steering forces, position updated from velocity each frame
- Toroidal wrapping — boids that exit one screen edge reappear on the opposite side
- Min speed clamp — ensures boids always move, which prevents degenerate zero-velocity states
- Inverse distance separation — more physically plausible than uniform separation so nearby boids repel harder
- Reynolds, C. W. (1987). Flocks, Herds, and Schools: A Distributed Behavioral Model. SIGGRAPH '87