This entry is part of 9 in the series Steering Behaviors

In the last post in the steering behaviors series, we looked at obstacle avoidance. This time we will explore path following. We will be using the Vector2D.as and Vehicle.as classes for this. If you don’t have them, you should get them. This post is based on Craig Reynold’s article Steering Behaviors For Autonomous Characters.

Path Following

Path Following, click to watch

Path following is used to simulate natural movement through a path. It is different from a train because a train is stuck on the track. The vehicle following these paths are free to move about and it creates a more natural, curvy motion.

Path following is rather simple. Given an array of waypoints (a Vector2D), the vehicle goes to the first one. When it is close enough to the first waypoint, its goal becomes the next waypoint and the cycle continues until it has gone through every waypoint.

But how do you go to a way point? Its actually simple, Seek it!

In code, path following looks like this:


private var index:int = 0;//the current waypoint index in the path array

public function followPath(path:Array):void {
if(index >= path.length){//if you have finished with the path
velocity.multiply(0.9);//slow down
return;//quit
}//otherwise
var waypoint:Vector2D = path[index];//get the current waypoint
var dist:Number = waypoint.distance(position);//get the distance from the waypoint
if(dist < 10){//if you are within 10 pixels of the waypoint(can be adjusted based on your needs)
index++;//go to the next waypoint
return;//quit for now
}
seek(waypoint);//otherwise, seek the current waypoint
}

And thats all there is to path following. It looks really cool and has plenty of uses.

To play with path following, click here.

Series Navigation