How to get the path of a NavigationAgent towards a certain point

Godot Version

v4.3.stable.mono.official [77dcf97d8]

Question

As the title says I’m trying to get the navigationAgent’s path towards a certain point, and then finding the lenght of that path. This is what I’m doing now:

   npc.pf.TargetPosition = position;
   var path = npc.pf.GetCurrentNavigationPath();
   GD.Print(path.Length);
   if (path.Length == 0) continue;
   lenght += (path[0] - npc.sheet.GlobalPosition).Length();
   for (int i = 0; i < path.Length-1; i++)
    {
           lenght += (path[i+1] - path[i]).Length(); 
    }

The problem is that path.Lenght seems to always be 0. So what am I doing wrong?

do you have a navigation mesh setup?

Yes, I do. I already have set up a script for the AI which uses navigation and it works just fine for making the ai navigate toward the player.

I should have mentioned it in the original post, but basically what I’m trying to do here is to have the ai search for the closest point with line of sight to the player. So this is a static function outside of the AI script which takes the ai script as an argument, and for each point in a grid (which I create in another function) it checks wether the point has line of sight to the player, and then I try to calculate the path lenght from the AI to the point, in order to check which is closest.

The nav agent also has a method " distance_to_target()". Maybe this is better

1 Like

Thanks, this seems to work. I would still like to know the issue with my code from before, but this solves my problem.

1 Like

The thing is that path is a PackedVector2Array and i cant find a property thats called length on the PackedVector2Array-docs, but if it doesnt exist its supposed to throw an error, isnt it?

I may be wrong, but it looks like in C# GetCurrentNavigationPath gives a regular Vector array, not a packed array

If thats true the docs say that the size of an array is recieved by calling “.size()” and it doesnt show a length property. Or is this also different for C#?

Yes, in c# you use array.Length to get the size of the array. I just did a test with an array I declared myself and it works

Then im not sure why your path is always 0