4

Having an issue i think i know why it is happening but not the correct way to get around the issue.

My Nav Mesh agent picks a random point in a circle and walk towards it for a random amount of time, when the position is valid it looks normal like this. enter image description here

But every so often the agent picks a spot it cant walk to and just stands there for the time it has been allotted to walk for and then picks another and moves again, while it cant walk this happens.

enter image description here

I know that the reason it is not moving is because the path is not valid (or at least i think that is why.)

But i have tried implementing something like this with no luck.

private void moveTowardsWaypoint()
    {
        agent.ResetPath();
        Vector3 newPosition = new Vector3(randomDirection.x, 0,        randomDirection.y) + transform.position;
        NavMeshPath path = new NavMeshPath();
        Debug.Log(agent.CalculatePath(newPosition, path));
        if(agent.CalculatePath(newPosition, path) == false)
        {

            agent.ResetPath();
            StopCoroutine(walkTime());
            pickWayPoint();
        }
        else
        {
            agent.SetDestination(newPosition);
        }

    }
bSky
  • 187
  • 2
  • 12

1 Answers1

4

When you're doubting the best way to manipulate Unity's components, why not consult their API documentation?

You can check if a world position (such as your random scatter point) is on the NavMesh with a check like so: NavMesh.Raycast(point, point, out navHit)

This attempts to trace a raycast from position 'point' to itself, returning false if no NavMesh is generated, the point is below the mesh or too far above it.

Then you can find the closest edge to this point with the following: NavMesh.FindClosestEdge(point, out navHit)

If true - a closest edge is found, the valid waypoint position will be stored in navHit.position.


If your diagrams are anything to go by, it looks like you've got some areas of the NavMesh that aren't connected to the area your agent resides on.

You should consider either:

  • Stop these unconnected areas from having a NavMesh generated
  • Connect these areas to the rest of the NavMesh via OffMeshLinks
  • Consider additional handling for NavMesh.FindClosestEdge(), such as adding an additional step that generates a path to validate if the origin and destination are on the same mesh. If they are not (and the path is invalid), some extra steps such as moving the point and re-testing until a valid path is found.
BMac
  • 463
  • 3
  • 8
Happy Apple
  • 726
  • 4
  • 13