Unity click to move with navmesh and navmesh agent
If you’ve played any classic rpg where the character moves around the level by click on the ground to navigate to that location, then you are in for a treat.
In this blog post, I’ll give you an example of how implement this functionality in Unity using navmesh agents.
Let’s take a look at this example class which we will call AgentClickToMove.
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class AgentClickToMove : MonoBehaviour
{
NavMeshAgent agent;
RaycastHit hit = new RaycastHit();
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if(Input.GetMouseButtonDown(0)){
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray.origin, ray.direction, out hit)){
agent.destination = hit.point;
}
}
}
}