Cohesion
Cohesion produces a steering force that moves a vehicle toward the center
of mass of its neighbors. See Figure 3.16, bottom. A sheep running after its
flock is demonstrating cohesive behavior. Use this force to keep a group of
vehicles together.
This method proceeds similarly to the last, except this time we calculate
the average of the position vectors of the neighbors. This gives us the cen

ter of mass of the neighbors — the place the vehicle wants to get to — so it
seeks to that position.
Vector2D SteeringBehaviors::Cohesion(const std::vector<Vehicle*>& neighbors)
{
//first find the center of mass of all the agents
Vector2D CenterOfMass, SteeringForce;
int NeighborCount = 0;
//iterate through the neighbors and sum up all the position vectors
for (int a=0; a<neighbors.size(); ++a)
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is a neighbor
if((neighbors[a] != m_pVehicle) && neighbors[a]>IsTagged())
{
CenterOfMass += neighbors[a]>Pos();
++NeighborCount;
}
}
if (NeighborCount > 0)
{
//the center of mass is the average of the sum of positions
CenterOfMass /= (double)NeighborCount;
//now seek toward that position
SteeringForce = Seek(CenterOfMass);
}
return SteeringForce;
}
You might be a little disappointed that I haven’t included demos for separa

tion, cohesion, and alignment. Well, there’s a reason for that: Like Itchy
and Scratchy, they are not particularly interesting on their own; they are
much better appreciated when they are combined, which takes us nicely
into flocking.
How to Create Autonomously Moving Game Agents  117
Group Behaviors