The principles behind flocking behaviors were first demonstrated in a computer simulation in 1986 by Craig Reynolds. Flocking is an example of emergent behavior, which I touched on briefly in an ealier post about Conway’s Game of Life.

Flocking behaviors are a lot of fun to play with, but simulating them can be fairly processor intensive. In an earlier post, I talked about using proximity grids to increase performance in this type of simulation. In the demo at the bottom of this post, I have employed a proximity grid and an implementation of verlet integration to control the particle dynamics.

One of the problems I ran into when combining flocking behaviors with proximity grids is that flocking tends to subvert the ways in which proximity grids optimize. A proximity grid reduces processing by making it easy to skip any inter-agent reactions on agents which are far apart. Flocking on the other hand tends to take agents and clump them together into small areas, thereby thwarting some of the benefit of a proximity grid. This is not to say that the proximity grid doesn’t help, because it does, but a proximity grid is more effective in cases where particles are scattered somewhat evenly across an area. I was unable to simulate as many particles in this demo as I did in the proximity grid demo partly because of the clumping nature of flocks, but mostly because of the need to examine the direction in which a particle is heading (a costly operation).

Figure 1. Agents react to near neighbors according to the basic priniciples of flocking. The length of an agent’s tail is based on its current velocity.

The core principles of flocking are alignment, separation and cohesion. Each individual agent (e.g., particle, sprite) operates autonomously by following these 3 basic rules. Each agent can only “see” agents near them (their neighbors). Agents will avoid close contact with neighbors (separation), they will attempt to travel in the same direction as their neighbors (alignment), and they will attempt to navigate towards the average position of their neighbors (cohesion). By employing these 3 basic rules, a wide variety of complex group behaviors emerge.

I’ve built a simple demonstration of flocking in Actionscript which you can view at the bottom of this post. This demo requires Flash Player 9 or later.

Figure 2. Holding the mouse button down will attract the agents, releasing the mouse button returns them to their regular behavior.