AI agent spinning in place at edge of graph when target is outside recast graph

  • A* version: [5.2.5]
  • Unity version: [2022.3.53]

3D game using recast graphs. Using AIPath with a seeker and funnel modifier.

I have some AI agents that will chase the player. The target is being set to the player’s position. The player however can move outside of the recast navmesh as the AI agent can’t reach all areas of map like the player can. The AI agent in these situations moves to the very edge of the graph closest to the player and instead of stopping it kind of spins around in place for a bit before finally stopping. Spinning lasts for like a second or 2, but doesn’t look great.

Is there anything that can be done so that if the target destination is outside the navmesh the agent will go to the closest spot it can get and then just stop instead of spinning in place for a bit before stopping?

I’m pretty sure this could be done with a few lines of code yes- it sounds like they’re going to the edge and then continuing to try and go to the player for a bit?

So something like this could be called when the player moves a certain distance, so when they walk off their position is set to the closest point.

if (graph.IsPointOnNavmesh(target.transform.position)){
    // Is in range, so go directly to it
    agent.destination = target.transform.position;
} else {
    // Isn't in range, so go to closest point
    // You could also substitute this with their last known position instead of the closest point
    agent.destination = graph.GetNearest(target.transform.position, null, Mathf.Infinity);
}

After that you could change their targets or remove it altogether so they don’t constantly try and set a new position. Does that work in your case?

Thanks for the suggestion! Using isPointOnNavMesh combined with isPathPossible has helped a lot.

I’ve resolved most of the issues, but there’s one last problem I’m trying to figure out: finding the closest reachable node to the target that still has a valid path. For example, imagine the target is on the other side of a wall. Since there’s a navmesh on both sides of the wall, isPointOnNavMesh will return true for the target, even though the AI can’t reach it. Meanwhile, isPathPossible correctly returns false.

What I need is a way to determine the closest point to the wall that the AI can still reach, so the AI doesn’t keep trying to navigate to an unreachable point on the other side. Essentially, I want to find the last node in a walkable path when the target itself isn’t reachable. Any suggestions?