Is it possible to lerp through a navmesh path?

Hello,
I am trying to find a way to control how far along a gameobject is in its path. Like 0% would be the start location and 100% would be at the end destination. I want to be able to control the rate at which it moves through the path and directly set its position along the path by changing this percent value. Is this possible with navmeshes/agents? I know I can do something like this with lerp, but I dont see that functionality in the agent class.

Thanks.

I don’t really use the NavMesh in Unity, and go with a 3rd party option.

And looking at the documentation there doesn’t appear to be a built in function to do what you’re asking.

But you DO get an array of all the points on the path:

And with this you can lerp between each individual point with Vector3.Lerp.

And if you summed up all the distances between every point in the path, you could calculate between which 2 nodes you’d be for any given ‘t’ in your psuedo-lerp function, and then lerp between the 2 points as necessary. Something along the lines of:

public static Vector3 ArrayLerp(Vector3[] v, float t)
{
    if(t <= 0f) return v[0];
    if (t >= 1f) return v[v.Length - 1];
   
    //this is completely unoptimized since it's calculating total distance every time
    //just slapped together for example purposes
   
    float len = 0f;
    for(int i = 1; i < v.Length; i++) len += Vector3.Distance(v[i], v[i-1]);
   
    float dt = len * t;
    float d = 0f;
    for(int i = 1; i < v.Length; i++)
    {
        float distanceBetweenPoints = d + Vector3.Distance(v[i], v[i-1]);
        if(dt < d + distanceBetweenPoints)
        {
            t = (dt - d) / distanceBetweenPoints; //get the percentage distance between v[i-1] and v[i]
            return Vector3.Lerp(v[i-1], v[i], t);
        }
        d += distanceBetweenPoints;
    }
   
    return v[v.Length - 1];
}

This is untested, unoptimized, code written directly into the browser. No promises of it working, use for example purposes only.

1 Like

Thanks! This was a very informative comment. Just out of curiosity, is there any 3rd party pathfinding systems that can do what I am try to do?

Not directly that I’m aware of. But pretty much all path finding systems will return an array of points on the path. And a system like @lordofduct 's can be used on any array of points.