How to find the best target?

Hello @all,

i use a* to move my units.
But now my units have 3 targets. They should check which of the target is the nearest (based on the way to the target).
How to check this? Can i Precalculate a paths length?

Thanks!

Hi

You can use a multi target path.
See http://arongranberg.com/astar/docs/class_seeker.php#a811996024eca2a032ad58c847ee2871f

A multi target path will calculate the path from one start point to multiple target points and either return just the shortest one or return all of them (depending on the parameters you specify).

Check out the “Path Types” example scene.

Multi target paths are only available in the pro version however. If you only have the free version you will have to manually calculate each path and compare the lengths.

Ah thanks, thats really nice.
In future i will buy/use the pro, to use this in the finished game.

But for testing issues i would do it manually.
Can you give me a example how to calculate a path manually and assign just the shortest to the unit?

Best regards!

Hi

Ok. This is not particularly efficient since it blocks for results instead of letting the system calculate for a few frames but anyway.

ABPath shortest = null;
foreach (var target in targets) {
     var path = ABPath.Construct(transform.position, target.position, null);
     AstarPath.active.StartPath(path, true);
     // Block until the path is complete, not particularly efficient
     AstarPath.WaitForPath(path);
     if (shortest == null || path.GetTotalLength() < shortest.GetTotalLength()) {
         shortest = path;
     }
}
// Apply any modifiers to e.g smooth out the path
seeker.PostProcess(shortest);
// Done!
// Shortest path is now stored in the "path" variable

Thanks for your example, it helped me out!