I've taken the A* Algorithm from this example XNA Pathfinder Example so that it will be able to plot a path for a moving goal.
The issue I'm having is that it will go in the right general direction but it will keep going back and forth in a line. I've changed the method so that it calculates a new path every half a second, clear out the previous points from the list and adds the new points to and from what I have debugged I can't find any issue with the points being added to the queue, to be honest I don't have the foggiest idea what is going wrong :/
This is the field where the waypoints are being held for the character
private Queue<Vector2> waypoints = new Queue<Vector2>();
This section is in the update loop and deals with the plotting a new path and laying out the new one onto the list mentioned above.
timer += gameTime.ElapsedGameTime;
if (timer.Seconds >= 0.5)
{
timer = TimeSpan.Zero;
pathFinder.NewPath(position);
}
if (pathFinder.SearchStatus == SearchStatus.PathFound)
{
waypoints.Clear();
foreach (Point point in pathFinder.FinalPath())
{
Waypoints.Enqueue(level.MapToWorld(point, true));
}
moving = true;
}
This section is where the waypoints are either taken off or used to set the new position of the character.
if (moving)
{
// If we have any waypoints, the first one on the list is where
// we want to go
if (waypoints.Count >= 1)
{
destination = waypoints.Peek();
}
// If we’re at the destination and there is at least one waypoint in
// the list, get rid of the first one since we’re there now
if (AtDestination && waypoints.Count >= 1)
{
waypoints.Dequeue();
}
if (!AtDestination)
{
direction = -(position - destination);
//This scales the vector to 1, we'll use move Speed and elapsed Time
//to find the how far the tank moves
direction.Normalize();
position = position + (direction * MoveSpeed * elapsedTime);
}
}