Flocking Animation
A boids/flocking simulation animation that demonstrates emergent behavior through simple rules: separation, alignment, and cohesion. Each boid follows these rules to create natural, organic movement patterns.
Preview
Watch the boids move in organic, flocking patterns. The animation adapts to your design system colors and theme.
Features
- Boids/flocking simulation with three core behaviors: separation, alignment, and cohesion
- Uses design system color tokens for dynamic theming
- Responsive canvas that adapts to container width
- Spatial grid optimization for efficient neighbor detection
- Wraparound edges for continuous movement
- Performance optimized with configurable boid count
Usage
Import and use the FlockingAnimation component:
import FlockingAnimation from "@/components/lattice/FlockingAnimation";
export default function MyComponent() {
return (
<div className="w-full">
<FlockingAnimation />
</div>
);
}Configuration
The animation automatically reads from CSS custom properties:
--surface- Background color--on-surface- Boid color
The animation height is fixed at 480px, and the width adapts to the container. The component handles theme changes automatically and includes proper cleanup on unmount.
Implementation Details
Boids Algorithm
The flocking behavior is achieved through three simple rules applied to each boid: separation (avoid crowding neighbors), alignment (steer towards average heading of neighbors), and cohesion (steer towards average position of neighbors). These rules create complex, emergent group behaviors.
Spatial Grid
To optimize performance, the animation uses a spatial grid system that divides the canvas into cells. Each boid only checks neighbors within its own cell and adjacent cells, dramatically reducing computational complexity from O(n²) to O(n).
Force-Based Movement
Each boid has velocity and acceleration vectors. Forces are calculated based on the three behaviors, then applied to acceleration. The acceleration is integrated into velocity, and velocity updates position. This creates smooth, natural movement patterns.
Rendering
The animation is rendered on an HTML5 canvas element. Each boid is drawn as a small triangle oriented in its direction of movement. The canvas is cleared and redrawn on each animation frame for smooth motion.