Loading point graph from file at run time

Hello. I’m pretty new to pathfinding, so I’m sorry if this sounds easy or dumb.

I’m making a game that’s 2D, top down. Basically it’s displaying a map, and I need to make paths between all the intersections. A point graph sounds perfect. The problem is some of the points will be far apart, as in a limited access highway, and some close together. So just doing a scan where it connects them by distance won’t work.

Another problem is that I need to be able to download new maps as the player progresses and load them into the same scene. Going though the example provided it looks like the number of nodes and their positions is done at design time. All that will change with each map they download, so it’s not known now.

What’s the best way to do this?

I wrote some code that loads in the node’s locations and the connections between them, and I can see the paths in the Unity editor. But I can’t get anything to follow it. Also, the paths just show up as white lines, not colored like I see in some of the other examples. Is that trying to tell me something?

Does anyone have any sample code for something like this I could look at? I’ve been programming since the 1980’s, but I guess I’m getting too old for it or something, because I’ve got over a week in trying to make it work and I’m little closer today than when I started. :frowning:

Any push in the right direction would be GREATLY appreciated!

Hi

If you want to construct a graph arbitrarily you can either write a custom graph generator (see http://arongranberg.com/astar/docs/writing-graph-generators.php) or perhaps more easily you can use a point graph.

 // Add a work item to make sure that the graph is not modified at the same time as pathfinding is running
 AstarPath.active.AddWorkItem(new AstarWorkItem((context, force) => {
     var graph = AstarPath.active.astarData.pointGraph;
     var node1 = graph.AddNode((Int3)new Vector3(0,0,0));
     var node2 = graph.AddNode((Int3)new Vector3(10,0,0));
    
     // costMagnitude is just a helper, it is the (Int3) distance between the nodes rounded to an integer
     node1.AddConnection(node2, (node1.position-node2.position).costMagnitude);
     node2.AddConnection(node1, (node1.position-node2.position).costMagnitude);

     // Necessary to recalculate some information used by the system. This will make the nodes the correct color in the scene view
      
     context.QueueFloodFill();
     return true;
 }));

(I haven’t actually tested this code, but I think it should work)

Thank you!

I had to change a couple of things, but that put me over the hump and it’s all working now. :smiley:

If anyone else needs the complete code to load a point graph from text files at run time, let me know and I’ll post the code.

1 Like