Friday, November 18, 2016

c# - Pathfinder not acting correctly


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 waypoints = new Queue();

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);
}
}


Answer



Note: I happened upon this because "Community" bumped it and I see that my comment was helpful so I figured I'd post it as an answer.




Is it possible that when it recalculates the next best position, it thinks going "forth" is a good idea so it goes that way. Then, when it checks a half second later, it thinks "back" is a good idea and goes back that way since you're erasing the old path?

As John McDonald described in the comments, to fix this you could weight the points already on the path so that it's more likely to follow the previous path but isn't necessarily stuck to it.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...