A* Pathfinding Project

2D Turn-based movement


#1

I’ve just downloaded the free version. I would like to implement this asset in my 2D Turn-Based strategy game. For that, I would like to implement my own movement method. My question is, How can I get an array of tiles of the found path?


#2

start is the vector of your starting tile
end is the vector of your ending tile
path is the array of vectors(of the tile positions)

ABPath path2 = ABPath.Construct(transform.position, End, null);
AstarPath.StartPath(path2);
path2.BlockUntilCalculated();
path = path2.vectorPath;


#3

See also https://arongranberg.com/astar/docs/callingpathfinding.html

The result is stored in the Path.path list (a list of nodes) and the Path.vectorPath list (a list of Vector3 coordinates of the points the path passes through).


#4

Thanks for the reply.
Now, could you give me a general idea about what would be the most efficient way of extracting an array of tiles based on the coordinated I get from the found path?
I have an array of GameObjects that represents a grid, and I have a list of Vector3 that I get from p.vectorPath that represents the found path. Looping through the grid array and comparing each tile position to the list of Vector3 won’t work.

Or, is there a way to instead of p.vectorPath being a list of vectors, I can get back a list of coordinates on the nodes grid, for example, Grid[2][4] - Grid[2][5] and so on.


#5

GridNode and it’s base have some coordinate variables:
https://arongranberg.com/astar/docs/gridnode.html#XCoordinateInGrid
https://arongranberg.com/astar/docs/gridnode.html#ZCoordinateInGrid

then you can loop the nodes in path and use something like this:
GridNode gNode = p.path[i] as GridNode;
Grid[gNode.XCoordinateInGrid][gNode.ZCoordinateInGrid]

For extra efficiency, this combined one is useful if you want to use a single dimension array for all nodes:
https://arongranberg.com/astar/docs/gridnode.html#NodeInGridIndex


#6

Thanks very much for the answer. I still have one problem. The path is in the opposite direction vertically i.e. If the endPos is below the startPos the path goes up and vice versa. It seems that the Graph is starting from the bottom left corner instead of top left?!


#7

Looking downwards in 3D, Unity does start it’s X and Z coordinates from the lower left, so the graphs tend to follow that.

If you know the total height, you should be able to reverse a coordinate something like this: [(GridHeight-1) - gNode.ZCoordinateInGrid]


#8

In addition to what @Hunted says, you can rotate the graph so that the origin is in the top left if you so desire.


#9

Thanks so much for the help guys.