Hi!
I am writing a game in XNA game studio,
it's a 2d game where the AI needs some type of path finding. I have choose to use Dijkstra's algorithm and it seems to work very good, except when the goal is at the opposite part of the map. Then I get some serious performance problem and it can take up to a minute or even worse. (A+ means that you can go in four directions and not like a cross A*.) I guess it's the priority queue that is the bottle neck but I don't know for sure.
The priority queue I use can be find at:
http://blogs.msdn.com/b/ericlippert/archive/2007/10/08/path-finding-using-a-in-c-3-0-part-three.aspx[
^]
The map consist of a multi array which have some 'gameObjects' in it.
All 'gameObjects' inheriting the interface IPathSquare which can tell if the position is walkable/free.
Here's the interface.
namespace PathLib
{
interface IPathSquere
{
bool isFree();
}
}
Here's the path finding code, note that the PriorityQueue comes from the link above.
namespace PathLib
{
class PathFinding
{
private IPathSquere[,] map;
public Point[] findPath(Point start, Point finish)
{
if (!isInMap(start) || !isInMap(finish))
return null;
PriorityQueue<int, LinkedList<Point>> pq =
new PriorityQueue<int, LinkedList<Point>>();
LinkedList<Point> lst = new LinkedList<Point>();
lst.AddLast(start);
pq.Enqueue(1, lst);
while (!pq.IsEmpty)
{
lst = pq.Dequeue();
Point curPos = lst.Last.Value;
if(curPos.Equals(finish))
return lst.ToArray<Point>();
Point[] temp = { new Point(curPos.X-1, curPos.Y),
new Point(curPos.X+1, curPos.Y),
new Point(curPos.X, curPos.Y-1),
new Point(curPos.X, curPos.Y+1)
};
foreach (Point p in temp)
{
if(isInMap(p) &&
map[p.X,p.Y].isFree() &&
!lst.Contains(p))
{
LinkedList<Point> tLst = new LinkedList<Point>(lst);
tLst.AddLast(p);
pq.Enqueue(tLst.Count, tLst);
}
}
}
return null;
}
public IPathSquere[,] Map
{
set { map = value; }
}
private bool isInMap(Point pos)
{
int rows = map.GetLength(0);
int cols = map.GetLength(1);
return 0 <= pos.X && pos.X < cols
&& 0 <= pos.Y && pos.Y < rows;
}
}
}
Maybe I should mention that the lag starts to be very heavy with a map like 20*15 squares if there is many walkable/free. So is it possible to get better performance (yes it must be..) and how can I achieve that.
Thanks in advance // WaZoX