How to use ai.remainingDistance?

Hi, I just wanted to know how I can use the ai.remainingDistance function. I’m not really sure how it works but it looks like I will need something like that.

What I’m trying to do is stop halfway when going to my destination, so ill be using ai.isStopped and the ai.remainingDistance to make this work from the looks of it. Sometimes I might need to do a logic or some alert when I’m only 20% towards my destination, or 80% near my destination and so on.

Just a simple example would be great. Thanks!

Hi

The remaining distance is just a world space distance, not a percentage. If you need to do something based on a percentage then save the remaining distance property and check if the current one is lower than a specific fraction. Like this

float maxDistance = 0;

void OnStartedMoving() {
    maxDistance = ai.remaningDistance;
}

void Update () {
    // Checking for the maximum distance every frame is useful since it handles the cases where
    // a: the world changed and the distance is suddenly much larger
    // b: the path took a few frames to calculate so the original ai.remainingDistance value was not very accurate
    maxDistance = Mathf.Max(maxDistance, ai.remainingDistance);

    if (ai.remainingDistance < 0.2*maxDistance) {
        Debug.Log("Less than 20% remaining since OnStartedMoving was called");
    }
}

Thanks, I tried that but it seems to launch the debug right from the start as my AI starts moving(when its clearly not 20% remaining etc).

I also had a debug log to keep track of maxDistance but it seems to always be on infinity.

Right. It will return +infinity when the agent has no path yet.

float maxDistance = 0;

void StartMoving(Vector3 destination) {
    ai.destination = destination;
    ai.SearchPath();
    maxDistance = 0;
}

void Update () {
    if(!ai.pathPending) {
        // Checking for the maximum distance every frame is useful since it handles the cases where
        // the world changed and the distance is suddenly much larger
        maxDistance = Mathf.Max(maxDistance, ai.remainingDistance);

        if (ai.remainingDistance < 0.2*maxDistance) {
            Debug.Log("Less than 20% remaining since OnStartedMoving was called");
        }
    }
}
1 Like

Awesome, that works now. Thank you.

Also could I just get a clarification on “ai.pathPending” and what it does? is it something that just waits to get a path for ai?

1 Like

You can find that in the documentation here: https://arongranberg.com/astar/docs/iastarai.html#pathPending

Will do that, thanks for the help again.