I've recently started playing around with AI and Unity's built in pathfinding. So far I haven't had any bigger troubles with it but yesterday I imported a mountain model with a path going from it's base to the very top.
My AI game object consists of Rigidbody (set to kinematic), Capsule Collider and a NavMesh Agent. I generated the NavMesh and set max slope to 40 degrees and the AI navigates just fine when it follows my player or walks along designated paths (waypoints) but when I try to pick a random position on the NavMesh in AI's radius it glitches out and starts shaking after few seconds, usually when the destination is close to NavMesh's edge. I've captured two videos of it and I'm struggling to fix this since yesterday.
I've tried removing the Rigidbody completely, changing obstacle avoidance settings, lowering the maximum slope but nothing worked so far.
This is how it looks like:
The code I use to get random position:
void ControlRandomWander()
{
float pointDist = Vector3.Distance(currentWanderPos, transform.position);
if(pointDist < 2f || currentWanderPos == Vector3.zero)
{
wanderWaitTimer += Time.deltaTime * 15;
anims.LookAround(true);
if (wanderWaitTimer >= wanderWaitTime)
{
Vector3 randPos = GetRandomPositionAroundTarget(transform.position, -wanderRadius, wanderRadius);
NavMeshPath pth = new NavMeshPath();
NavMesh.CalculatePath(transform.position, randPos, agent.areaMask, pth);
float pathDist = 0f;
if (pth.status == NavMeshPathStatus.PathComplete)
{
for (int i = 0; i < pth.corners.Length - 1; i++)
{
pathDist += Vector3.Distance(pth.corners[i], pth.corners[i + 1]);
}
Debug.Log(pathDist);
if (pathDist <= wanderRadius)
{
currentWanderPos = randPos;
wanderWaitTime = Random.Range(wanderWaitMin, wanderWaitMax);
anims.LookAround(false);
wanderWaitTimer = 0;
MoveToPosition(randPos, true);
}
}
}
}
else
{
if (agent.destination != currentWanderPos)
{
MoveToPosition(currentWanderPos, true);
}
}
}
Vector3 GetRandomPositionAroundTarget(Vector3 pos, float minRange, float maxRange)
{
float offsetX = Random.Range(minRange, maxRange);
float offsetZ = Random.Range(minRange, maxRange);
Vector3 orgPos = pos;
orgPos.x += offsetX;
orgPos.z += offsetZ;
NavMeshHit hit;
if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
{
Debug.Log(hit.position);
return hit.position;
}
Debug.Log(hit.position);
return pos;
}
I would really appreciate any help sorting out this issue.
Turns out NavMesh.SamplePosition
doesn't take NavMesh Agent radius into account so the agent can't ever reach it.
I managed to fix it by moving the hit.position by half of agent's radius away from the edge.
if(NavMesh.SamplePosition(orgPos, out hit, 5f, agent.areaMask))
{
Vector3 ret = hit.position;
Vector3 pathDir = pos - ret;
ret += pathDir.normalized * (agent.radius / 2);
return ret;
}