I’m trying to move a Rigidbody2D with directions provided by the NavMeshAgent. Here’s what I have as my code:
public class Test : MonoBehaviour
{
NavMeshAgent enemyAgent;
Rigidbody2D enemyRB;
public GameObject player;
private void Start()
{
// Initialize NavMeshAgent
enemyAgent = GetComponent<NavMeshAgent>();
enemyAgent.updateRotation = false;
enemyAgent.updateUpAxis = false;
enemyAgent.updatePosition = false;
// Initialize RigidBody2D
enemyRB = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
enemyAgent.SetDestination(player.transform.position);
enemyRB.velocity = new Vector2(enemyAgent.nextPosition.x, enemyAgent.nextPosition.y);
}
}
I may be misunderstanding what nextPosition does, but I’m treating it like it’s a vector that, at that moment, is the direction towards the target (in this case, the player). I find, however, that the enemy GameObject just runs seemingly randomly up to the northeast.
Is this the way I should think about using the NavMeshAgent’s “directions” to move with a Rigidbody? Or is there a better way that accomplishes what I’m going for? Thank you!
EDIT: Worth noting as well, I am using a package that allows me to create a NavMesh in 2D, called NavMeshPlus, found here on GitHub: GitHub - h8man/NavMeshPlus: Unity NavMesh 2D Pathfinding