Of course! One of the most classic and visually satisfying examples of emergence is flocking behavior, famously modeled by Craig Reynolds' "Boids" algorithm.
The core idea is that complex, life-like flocking patterns can emerge from three very simple rules that each individual agent (or "boid") follows based only on its local neighbors.
- Separation: Steer to avoid crowding local flockmates.
- Alignment: Steer towards the average heading of local flockmates.
- Cohesion: Steer to move towards the average position of local flockmates.
No single boid knows where the "flock" is going. The flock's coherent movement is an emergent property of these simple, local interactions.
Here is a complete, well-commented Processing sketch that implements the Boids algorithm.
How to Use This Sketch
- Install Processing: If you don't have it, download it for free from processing.org.
- Create a New Sketch: Open Processing and paste the code below into the editor.
- Run: Click the "Run" button (the triangle).
You will see boids moving around the screen. Click the mouse to add new boids to the simulation!
The Processing Sketch: EmergentFlocking.pde
// Emergent Flocking Behavior (Boids)
// by Craig Reynolds
// A classic example of emergence where complex, life-like flocking arises
// from three simple rules applied to individual agents ("boids").
//
// THE THREE RULES:
// 1. Separation: Steer to avoid crowding local flockmates.
// 2. Alignment: Steer towards the average heading of local flockmates.
// 3. Cohesion: Steer towards the average position (center of mass) of local flockmates.
//
// Click the mouse to add new boids to the flock.
// The main list that will hold all the boid objects
ArrayList<Boid> flock;
void setup() {
size(800, 600); // Set the size of the window
flock = new ArrayList<Boid>();
// Add an initial group of boids to the system
for (int i = 0; i < 100; i++) {
// Add a new Boid at a random position
flock.add(new Boid(random(width), random(height)));
}
}
void draw() {
background(50, 50, 80); // A dark blue background
// Run every boid in the flock
// We pass the entire flock to each boid so it can check its neighbors.
for (Boid b : flock) {
b.run(flock);
}
}
// Add a new boid to the flock wherever the mouse is clicked
void mousePressed() {
flock.add(new Boid(mouseX, mouseY));
}
// Boid Class
// The class that defines the agent, its properties, and its behaviors.
class Boid {
PVector position; // Location
PVector velocity; // Speed and direction
PVector acceleration; // The force that changes velocity
float r; // Size for drawing
float maxForce; // Maximum steering force
float maxSpeed; // Maximum speed
// Constructor to create a new Boid
Boid(float x, float y) {
acceleration = new PVector(0, 0);
// Give it a random initial velocity
float angle = random(TWO_PI);
velocity = new PVector(cos(angle), sin(angle));
position = new PVector(x, y);
r = 3.0;
maxSpeed = 3;
maxForce = 0.05;
}
// The main run method, called in every frame from draw()
void run(ArrayList<Boid> boids) {
flock(boids); // Apply the three rules
update(); // Update the boid's position based on its physics
borders(); // Handle screen wrapping
render(); // Draw the boid
}
// Method to accumulate and apply forces from the three rules
void flock(ArrayList<Boid> boids) {
PVector sep = separate(boids); // Separation
PVector ali = align(boids); // Alignment
PVector coh = cohesion(boids); // Cohesion
// Arbitrarily weight these forces
sep.mult(1.5);
ali.mult(1.0);
coh.mult(1.0);
// Add the force vectors to acceleration
applyForce(sep);
applyForce(ali);
applyForce(coh);
}
// Method to update location
void update() {
// Update velocity
velocity.add(acceleration);
// Limit speed
velocity.limit(maxSpeed);
position.add(velocity);
// Reset acceleration to 0 each cycle
acceleration.mult(0);
}
// A method that calculates and applies a steering force towards a target
// STEER = DESIRED MINUS VELOCITY
PVector seek(PVector target) {
PVector desired = PVector.sub(target, position); // A vector pointing from the location to the target
desired.normalize();
desired.mult(maxSpeed);
// Steering = Desired - Velocity
PVector steer = PVector.sub(desired, velocity);
steer.limit(maxForce); // Limit to maximum steering force
return steer;
}
// Method to draw the boid as a triangle
void render() {
// The triangle points in the direction of velocity
float theta = velocity.heading() + PI/2;
fill(200, 100);
stroke(255);
pushMatrix();
translate(position.x, position.y);
rotate(theta);
beginShape(TRIANGLES);
vertex(0, -r*2);
vertex(-r, r*2);
vertex(r, r*2);
endShape();
popMatrix();
}
// Wraparound: When a boid goes off-screen, it reappears on the opposite side.
void borders() {
if (position.x < -r) position.x = width+r;
if (position.y < -r) position.y = height+r;
if (position.x > width+r) position.x = -r;
if (position.y > height+r) position.y = -r;
}
// --- THE THREE RULES ---
// 1. Separation
// Method checks for nearby boids and steers away
PVector separate(ArrayList<Boid> boids) {
float desiredSeparation = 25.0f;
PVector steer = new PVector(0, 0);
int count = 0;
// For every boid in the system, check if it's too close
for (Boid other : boids) {
float d = PVector.dist(position, other.position);
if ((d > 0) && (d < desiredSeparation)) {
// Calculate vector pointing away from neighbor
PVector diff = PVector.sub(position, other.position);
diff.normalize();
diff.div(d); // Weight by distance (the closer it is, the stronger the force)
steer.add(diff);
count++;
}
}
// Average the steering vector
if (count > 0) {
steer.div(count);
}
if (steer.mag() > 0) {
steer.normalize();
steer.mult(maxSpeed);
steer.sub(velocity);
steer.limit(maxForce);
}
return steer;
}
// 2. Alignment
// For every nearby boid, calculate the average velocity
PVector align(ArrayList<Boid> boids) {
float neighborDist = 50;
PVector sum = new PVector(0,0);
int count = 0;
for (Boid other : boids) {
float d = PVector.dist(position, other.position);
if ((d > 0) && (d < neighborDist)) {
sum.add(other.velocity);
count++;
}
}
if (count > 0) {
sum.div(count);
sum.normalize();
sum.mult(maxSpeed);
PVector steer = PVector.sub(sum, velocity);
steer.limit(maxForce);
return steer;
} else {
return new PVector(0,0);
}
}
// 3. Cohesion
// For the average position of all nearby boids, calculate steering vector towards that position
PVector cohesion(ArrayList<Boid> boids) {
float neighborDist = 50;
PVector sum = new PVector(0,0); // Start with empty vector to accumulate all locations
int count = 0;
for (Boid other : boids) {
float d = PVector.dist(position, other.position);
if ((d > 0) && (d < neighborDist)) {
sum.add(other.position); // Add location
count++;
}
}
if (count > 0) {
sum.div(count);
return seek(sum); // Steer towards the location
} else {
return new PVector(0,0);
}
}
// Helper function to apply a force to the boid's acceleration
void applyForce(PVector force) {
acceleration.add(force);
}
}