I am trying to get a NavMeshAgent to move to the position clicked by the mouse. Following the example provided in the documentation, I implemented this test class to control the agent:
public class PlayerController : MonoBehaviour {
public float clickMaxDist = 1000.0f;
public NavMeshAgent Agent;
void Update ()
{
// Click to move agent
if(Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 100);
if(Physics.Raycast(ray, out hit, clickMaxDist)) {
Agent.SetDestination(hit.point);
}
}
}
}
I must be missing something, because my rays only hit when I click right on top of the cylinder, which of course, isn’t very useful to move the agent around the map.
To test if I was casting the Rays correctly, I used Debug.DrawRay:
Which, to me, looks like everything should be working.
I’ve looked around this forum and googled for a while, but everyone seems to suggest similar methods for doing this. I don’t suppose I need to add a MeshCollider to my terrain mesh for this to work, or do I?
I also tried using NavMesh.Raycast in a similar fashion, also with no results.
Anyway, I am simply puzzled by this. If anyone could point me in the right direction, it would probably spare me a lot of time.
Thank you in advance.