I have created a navigation system using Rigidbody and NavMesh. There is an agent that tries to follow me around. It has a capsule collider, a script (see below), a Rigidbody, and a NavMeshAgent component. It works by running the NavMesh calculations, getting the coordinates for the next place to move, disabling the NavMesh, and moving there using MovePosition()
. This system works pretty well usually, but lately I have been experiencing problems. When the Agent moves around an obstacle, it pauses on the corners. I believe the reason for this is my code, especially my MovePosition()
function, but I don't know how to fix it.
using UnityEngine;
using UnityEngine.AI;
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float m_Speed = 3f;
public Transform goal;
public NavMeshAgent navMesh;
public float maxSpeed = 5f;
void FixedUpdate()
{
MoveToNextPosition();
}
void MoveToNextPosition()
{
navMesh.enabled = true;
if (navMesh.isOnNavMesh)
{
NavMeshPath path = new NavMeshPath();
if(navMesh.CalculatePath(goal.position, path))
{
navMesh.path = path;
}
}
Vector3 pos = navMesh.steeringTarget;
navMesh.enabled = false;
//Store user input as a movement vector
Vector3 distance = pos - transform.position;
Vector3 direction = distance.normalized;
float speed = rb.velocity.magnitude;
Debug.Log(direction);
rb.MovePosition(transform.position + direction * Time.deltaTime * m_Speed);
}
}
I have a big list of what the issues with the navmesh can be, hence I am posting it as an answer:
Open your navigation panel, if you can't find one or accidentally closed the tab, go to Window > AI > Navigation. The Navigation tab looks like this:
Open the Bake tab and set your agent's radius and height according to its dimensions. At the bottom, click to expand Advanced options. In that, there's a field Min Region Area, increasing the value increases the area around the static obstacles where the navmesh agent cannot move.