对于敌人,我每隔 x 秒在导航网格上设置一个随机位置,以便敌人随机走动。这是我的脚本:
随机点(来自统一文档)
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;
}
我的随机运动脚本:
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");
}
}
随机行走通常有效。然而,当导航网格代理接近导航网格的边界时,他似乎“突围”,然后被卡在他的位置上。他只是在导航网之外“四处颤抖”。(图像上的红线:路径)
看起来他们试图到达他们的位置,但无法再次进入导航网格。我不希望他们首先离开:)