Make an AI travel to a random point within reach, via random point inside a circle

It’s basically an extension of method 1. I’m trying to make my AI go to a point within a radius, but only if the path to that point is not too long. However, the code below is giving me an error (path has an invalid state). Seems like I’m misunderstanding how the seeker.StartPath works?

    private IEnumerator RoamAround()
    {
        while (validPathFound== false)
        {
            //Find random point within spawn-area
            Vector3 randomPoint = Random.insideUnitSphere * 5f;
            randomPoint.y = 0;
            randomPoint += spawnPosition;

            //Calculate the path to that random point
            AstarPath.StartPath(ABPath.Construct(transform.position, randomPoint, OnPathComplete));

            yield return null;
        }
    }

    private void OnPathComplete(Path path)
    {
        //Get the length of the path and only travel there if length is shorter than 2
        float length = path.GetTotalLength();
        if (length <= 2)
        {
            seeker.StartPath(path);   //<<< This doesn't work and gives me an error
            validPathFound= true;
        }
    }

I’m doing it like this because I read that RandomPath doesn’t work well with Recast Graphs and Navmeshes. Or should I resort to ConstantPath/Breadth-first search? To me the logic of the code above should also work, but I can’t get it to work.

Hi

You are trying to calculate the path twice. First you calculate it, and then you try to send it to the seeker to calculate it again. The seeker will complain about that.

If you want to do this for a recast/navmesh graph you will need to post-process the path using the funnel modifier. I would recommend attaching that to your agent and using this code:

void Start() {
    seeker = GetComponent<Seeker>();
    // Your movement script (e.g. AIPath/RichAI/AILerp)
    ai = GetComponent<IAstarAI>();
}

private IEnumerator RoamAround() {
    while (validPathFound== false) {
        //Find random point within spawn-area
        Vector3 randomPoint = Random.insideUnitSphere * 5f;
        randomPoint.y = 0;
        randomPoint += spawnPosition;

        //Calculate the path to that random point
        AstarPath.StartPath(ABPath.Construct(transform.position, randomPoint, OnPathComplete));

        yield return null;
    }
}

private void OnPathComplete(Path path) {
    // Apply the funnel modifier to simplify the path and make the length more accurate
    seeker.PostProcess(path);
    //Get the length of the path and only travel there if length is shorter than 2
    float length = path.GetTotalLength();
    if (length <= 2) {
        ai.SetPath(path);
        validPathFound= true;
    }
}