- Home /
NavMeshAgent not calculating shortest route.
Hi !
I'm having trouble with Unity's NavMeshAgent / NavMesh. My agent's do not seem to be finding the fastest route to their destination. Bellow are some screen shots of what I am experiencing.
Here is what I'm experiencing. Please ignore the tween paths (pink and bright red lines).
top image, the cube that is going through the gap was spawned closer to the end point. so it seems to have found the fastest path. The agent that was further back has decided to take the scenic route.
The middle image shows that it's consistent every time they spawn and I run the scene.
The bottom image shows the nav mesh itself. Ignore the light blue shade on the NavMesh I've have since removed that and still receive the same results.
Here are my NavAgent details:
I believe the code is unrelated. I've tried both updating their destinations with SetDestination and only setting it when I spawn them.
I just noticed the image of the NavMesh doesn't show the end point. The end point is on the NavMesh.
Answer by jstopyra · Jul 27, 2017 at 05:34 PM
Was this ever solved? I'm having the same issue and can't find a solution for it.
Answer by drewjosh · Oct 29, 2020 at 04:12 PM
There is a solution I found in the Unity Docs: NavMesh.CalculatePath
You can tell Unity to calculate the path new. Although it recommends to do it only every second, otherwise it could cause problems with frame rate:
// ShowGoldenPath
using UnityEngine;
using UnityEngine.AI;
public class ShowGoldenPath : MonoBehaviour
{
public Transform target;
private NavMeshPath path;
private float elapsed = 0.0f;
void Start()
{
path = new NavMeshPath();
elapsed = 0.0f;
}
void Update()
{
// Update the way to the goal every second.
elapsed += Time.deltaTime;
if (elapsed > 1.0f)
{
elapsed -= 1.0f;
NavMesh.CalculatePath(transform.position, target.position, NavMesh.AllAreas, path);
}
for (int i = 0; i < path.corners.Length - 1; i++)
Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.red);
}
}
@jstopyra (my answer is kinda late, but it's never too late)
Answer by Akvavit · Jul 27, 2017 at 07:06 PM
Well I'm no expert on the navmesh since I always make my own path finding but my guess is because it's not supposed to find the shortest route. Finding the shortest route is very expensive, and what pathfinding algorithms are usually doing (like A*) is finding a good path, fast. If you want the 100% the shortest path you probably want to look up Dijkstra's algorithm. But if it is a realtime (not turnbased) game I wouldn't use it since it is very expensive.
Your answer
Follow this Question
Related Questions
Recentering an infinite world that has a NavMesh. 0 Answers
Use Fog of War to Restrict NavMesh Per-Agent 0 Answers
NavMesh agent Pathfinding Zombies 1 Answer
How to use Unity's pathfinding system without NavMeshAgent controlling my character? 1 Answer
How to check if Navmesh finished baking realtime ( in playmode ) ? 1 Answer