Agent stops on edges

I’m using the following script to make the NPC wander around the nav mesh.

using UnityEngine;
using System.Collections;

public class Wander : MonoBehaviour {

public float wanderRadius;
public float wanderTimer;

private Transform target;
private UnityEngine.AI.NavMeshAgent agent;
private float timer;

// Use this for initialization
void OnEnable () {
agent = GetComponent<UnityEngine.AI.NavMeshAgent> ();
timer = wanderTimer;
}

// Update is called once per frame
void Update () {
timer += Time.deltaTime;

if (timer >= wanderTimer) {
Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
agent.SetDestination(newPos);
timer = 0;
}
}

public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask) {
Vector3 randDirection = Random.insideUnitSphere * dist;

randDirection += origin;

UnityEngine.AI.NavMeshHit navHit;

UnityEngine.AI.NavMesh.SamplePosition (randDirection, out navHit, dist, layermask);

return navHit.position;
}
}

Can anyone tell me why they might be stopping at the edge of the nav mesh? I’m relatively new to navmeshes and I’m not sure if I’m using something wrong or what

Well if you take random directions and your agent is already standing at an edge, it’s very easy to keep moving in a direction outside of the navmesh.
If you’re looking to make a bit more of a controlled wander, maybe set a few target positions your agent can wander between?

I agree with Yandalf, there’s a high likelihood of picking a position outside the bounds. and as you’re using a sphere, there’s also a good chance of choosing a position too far above or below the navmesh. I assume that you’ve tried setting wanderDistance to a small value - a large radius (e.g. 50 meters) equates to a lot of empty space. I’ve got something similar working, but I’m using a circular radius with a limited range of height (as the map is relatively flat and NPCs don’t move more than 1 “floor” at a time). It also greatly helps if the agent is “aware” of the map edges and/or as Yandalf suggests, constrain wandering around fixed positions or within a radius…