Game Development Reference
FIG 5.12 Flocking rules: (a) move
toward average group position, (b)
align heading with average group
heading, and (c) avoid others.
In 1986, Craig Reynolds developed an unparalleled simple algorithm for
producing flocking behavior in groups of computer characters. Through the
application of three rules, Reynolds developed coordinated motions such as
that seen in flocks of birds and schools of fish. The rules are applied to each
individual character in a group with the result of very convincing flocking
behavior. These rules (illustrated in Figure 5.12 ) include
moving toward the average position of the group
aligning with the average heading of the group
avoid crowding other group members
Flocking creates a moving group with no actual leader. The rules can be
increased to take into consideration moving toward a goal position or the effect
of wind. These rules are used to create a flock of birds in the following workshop.
Unity Hands On
Step 1. Download Chapter Five/flocking.zip from the Web site and
open the testFlock scene. Play. You will see a radar showing the
position of seagulls created with the globalFlock script attached to
the camera. To move the camera, use the arrow keys. This will allow
you to look at parts of the flock. Currently the seagulls do not move.
In the globalFlock script 100 seagulls are being created. If you want
more, change the value of 100. If your computer starts to slow you
may need to reduce the flock size.
Step 2. Open the flock script and add the code in Listing 5.15 .
Step 3. Attach the flock script to the SeagullPrefab in the Project.
Step 4. Play. Each seagull will have a random speed setting and be
flying in a straight line. You can use the arrow keys to follow the birds.
Step 5. Let's apply the first flocking rule to the population. Modify the
flock script as shown in Listing 5.16 .