A* Pathfinding Project

Calculate serval paths and pick the shortest


#1

Hello,

I am making an RTS style game using a point graph.
I spawn in an enemy and he wants to attack the nearest allied building.
So I find all allied buildings and calculate paths for each then sort by shortest distance and start using that one.
I am using AIPath for movement.
Right now i am using this

            foreach (var doodad in buildings)
            {
                Path path = ABPath.Construct(transform.position, doodad.transform.position, null);
                GetComponent<Seeker>().StartPath(path);
                path.BlockUntilCalculated();
                options.Add(path);
            }
       if (options.Any())
        {
            var order = options.OrderBy(p => p.GetTotalLength());
            ai.SetPath(order.First());
        }

But I get an error saying “ArgumentException: If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.”

Thanks!


#2

Hi

I would suggest using the MultiTargetPath

See https://arongranberg.com/astar/docs/multitargetpath.html

Make sure to set ai.canSearch = false if you are doing the path calculations yourself.


#3

Hmm unfortunately I am a student and I cant afford pro. Is there another option? I dont need to do any multi step process just go to the closest.


#4

Then I’d recommend not using the Seeker component as that component is designed for only one path request at a time. It will confuse the movement script.

foreach (var doodad in buildings) {
    Path path = ABPath.Construct(transform.position, doodad.transform.position, null);
    AstarPath.StartPath(path);
    options.Add(path);
}
foreach(var path in options) {
    path.BlockUntilCalculated();
    // Runs any modifiers you have attached
    seeker.PostProcess(path);
}
if (options.Any()) {
    var order = options.OrderBy(p => p.GetTotalLength());
    ai.SetPath(order.First());
}

#5

It looks like I cant call active.StartPath in my monobehavior because its static method. Would it be best to just have a static helper class handle that or is there a built in way to do this?


#6

Oops. It should be AstarPath.StartPath.


#7

Wow works great thank you so much.