For enemies, I set a random position on the nav mesh every x seconds, so that the enemies walk around randomly. Here my scripts:
Random point (from the unity docs)
bool RandomPoint (Vector3 center, float range, out Vector3 result)
{
for (int i = 0; i < 30; i++) {
Vector3 randomPoint = center + Random.insideUnitSphere * range;
NavMeshHit hit;
if (NavMesh.SamplePosition (randomPoint, out hit, 1.0f, NavMesh.AllAreas)) {
result = hit.position;
return true;
}
}
result = Vector3.zero;
return false;
}
My random movement script:
IEnumerator Walking ()
{
if (!isFollowingPlayer && isServer) {
Debug.LogError ("-- Start Walking --");
agent.speed = 2;
Vector3 randomDirection;
bool blocked = RandomPoint (agent.transform.position, walkRadius, out randomDirection);
NavMeshHit hit;
blocked = NavMesh.Raycast (enemy.transform.position, randomDirection, out hit, NavMesh.AllAreas);
if (!blocked) {
geileMethodeZumZeichnen (agent);
target = hit.position;
agent.SetDestination (hit.position);
geileMethodeZumZeichnen (agent);
Debug.LogWarning ("Go to " + hit.position);
}
if (blocked) {
Debug.LogWarning ("-- BLOCKED --");
yield return new WaitForEndOfFrame ();
} else {
Debug.LogWarning ("-- WAIT --");
yield return new WaitForSeconds (5f);
}
StartCoroutine ("Walking");
}
}
The random walking generally works. However when a nav mesh agent is close to the border of the nav mesh, it appears that he "breaks out" and is then stuck to his position. He only "jitters around" outside the nav mesh. (red lines on the image : path)
Looks like they try to reach their position but can not enter the nav mesh again. I don't want them to leave in first place :)