Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AI and Deep Learning by (50.2k points)

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 walks 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 can't 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 can't walk this happens.

enter image description here

I know that the reason it is not moving is that 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);

        }

    }

1 Answer

0 votes
by (108k points)

You have to request the agent to move to the valid navmesh position that's closest to the requested destination.

  • The path result may not available until after a few frames. Use pathPending to query for outstanding results.
  • If it's not feasible to find a valid nearby navmesh position (e.g. Scene has no navmesh) no path is requested. Use SetDestination and check the return value if you need to handle this case explicitly.

You can refer to the following link for more information regarding the NavMeshAgent:

https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.html 

You can also 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 sketch 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 - the closest edge is found, the valid waypoint position will be stored in navHit.position.

If you are looking to learn more about Artificial Intelligence then you visit Artificial Intelligence Tutorial and Artificial Intelligence Course. Also, if you are appearing for job profiles of AI Engineer or AI Expert then you can prepare for the interviews on Artificial Intelligence Interview Questions.

Browse Categories

...