Gamedev Hub

Boids (Flocking Simulation)

Developed by Craig Reynolds in 1986, Boids is an artificial life program that simulates the flocking behavior of birds. The complexity of the flock emerges from just three simple steering rules applied locally to each agent.

1. The Three Core Rules

1. Separation (Avoid Crowding)

Steer to avoid crowding local flockmates. This prevents boids from overlapping and ensures they have “personal space.”

2. Alignment (Match Velocity)

Steer towards the average heading of local flockmates.

3. Cohesion (Stay Together)

Steer to move toward the average position (center of mass) of local flockmates.

2. The Math of Steering

For each rule, we calculate a Steering Force: Steering = Desired_Velocity - Current_Velocity

The final force applied to the boid is: Total_Force = (Separation * w1) + (Alignment * w2) + (Cohesion * w3) Where w are weights used to tune the behavior (e.g., more separation makes the flock “loose”).

3. Implementation (C# Example)

Vector2 ComputeSteerForce(Boid agent) {
    var neighbors = spatialHash.GetNeighbors(agent.position, viewRadius);
    
    Vector2 sep = Separation(agent, neighbors) * weightSep;
    Vector2 ali = Alignment(agent, neighbors) * weightAli;
    Vector2 coh = Cohesion(agent, neighbors) * weightCoh;

    return sep + ali + coh;
}

4. Performance: The O(n²) Trap

A naive implementation where every boid checks every other boid will lag at ~500 agents.

5. Summary