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

Arrive
Seek is useful for getting an agent moving in the right direction, but often
you’ll want your agents to come to a gentle halt at the target position, and
as you’ve seen, seek is not too great at stopping gracefully. Arrive is a
behavior that steers the agent in such a way it decelerates onto the target
position.
In addition to the target, this function takes a parameter of the enumer
-
ated type
Deceleration, given by:
enum Deceleration{slow = 3, normal = 2, fast = 1};
Arrive uses this value to calculate how much time the agent desires to take
to reach the target. From this value we can calculate at what speed the
agent must travel to reach the target position in the desired amount of time.
After that, the calculations proceed just like they did for seek.
Vector2D SteeringBehaviors::Arrive(Vector2D TargetPos,
Deceleration deceleration)
{
Vector2D ToTarget = TargetPos - m_pVehicle->Pos();
//calculate the distance to the target position
double dist = ToTarget.Length();
if (dist > 0)
{
//because Deceleration is enumerated as an int, this value is required
//to provide fine tweaking of the deceleration.
const double DecelerationTweaker = 0.3;
//calculate the speed required to reach the target given the desired
//deceleration
double speed = dist / ((double)deceleration * DecelerationTweaker);
//make sure the velocity does not exceed the max
speed = min(speed, m_pVehicle->MaxSpeed());
//from here proceed just like Seek except we don't need to normalize
//the ToTarget vector because we have already gone to the trouble
//of calculating its length: dist.
Vector2D DesiredVelocity = ToTarget * speed / dist;
return (DesiredVelocity - m_pVehicle->Velocity());
}
return Vector2D(0,0);
}
Now that you know what it does, have a look at the demo executable.
Notice how when the vehicle is far away from the target the arrive behav
-
ior acts just the same as seek, and how the deceleration only comes into
effect when the vehicle gets close to the target.
How to Create Autonomously Moving Game Agents | 93
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