O'Reilly logo

Programming Game AI by Example by Mat Buckland

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

You can observe this behavior in action by running the Seek.exe execut
-
able. Click with the left mouse button to alter the position of the target.
Notice how the agent will overshoot the target and then turn around to
approach again. The amount of overshoot is determined by the ratio of
MaxSpeed to MaxForce. You can change the magnitude of these values by
pressing the Ins/Del and Home/End keys.
Seek comes in handy for all sorts of things. As you’ll see, many of the
other steering behaviors will make use of it.
Flee
Flee is the opposite of seek. Instead of producing a steering force to steer
the agent toward a target position, flee creates a force that steers the agent
away. Here’s the code:
Vector2D SteeringBehaviors::Flee(Vector2D TargetPos)
{
Vector2D DesiredVelocity = Vec2DNormalize(m_pVehicle->Pos() - TargetPos)
* m_pVehicle->MaxSpeed();
return (DesiredVelocity - m_pVehicle->Velocity());
}
Note how the only difference is that the DesiredVelocity is calculated
using a vector pointing in the opposite direction (
m_pVehicle->Pos()
TargetPos
instead of TargetPos m_pVehicle->Pos()).
Flee can be easily adjusted to generate a fleeing force only when a vehi-
cle comes within a certain range of the target. All it takes is a couple of
extra lines of code.
Vector2D SteeringBehaviors::Flee(Vector2D TargetPos)
{
//only flee if the target is within 'panic distance'. Work in distance
//squared space.
const double PanicDistanceSq = 100.0 * 100.0;
if (Vec2DDistanceSq(m_pVehicle->Pos(), target) > PanicDistanceSq)
{
return Vector2D(0,0);
}
Vector2D DesiredVelocity = Vec2DNormalize(m_pVehicle->Pos() - TargetPos)
* m_pVehicle->MaxSpeed();
return (DesiredVelocity - m_pVehicle->Velocity());
}
Notice how the distance to the target is calculated in distance squared
space. As you saw in Chapter 1, this is to save calculating a square root.
92 | Chapter 3
The Steering Behaviors

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required