- Home /
How to detect if NavAgent has reached hit.point? (2) Distance doesn't work?
Here's the new code:
float dist;
RaycastHit hit;
void Update()
{
if (Input.GetMouseButtonDown(1))
{
float dist = Vector3.Distance(agent.transform.position, hit.point);
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity))
{
agent.SetDestination(hit.point);
if (dist < .1f)
{
print("Destination reached");
}
}
}
And it doesn't work. The distance isn't really registered. The message "Destination reached" appears the second I click which is not what I want. The actual distance doesn't seem to matter at all. I want the message to only appear AFTER the agent has reached the hit.point.
Answer by Pokedlg3 · Dec 02, 2020 at 09:36 PM
You put if inside another if, this in your code makes the message appear only when you click the right mouse button. Try this:
float dist;
RaycastHit hit;
void Update()
{
if (Input.GetMouseButtonDown(1))
{
float dist = Vector3.Distance(agent.transform.position, hit.point);
}
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity))
{
agent.SetDestination(hit.point);
}
if (dist < .1f)
{
print("Destination reached");
}
}
No, it doesn't work unfortunately. I made the dist public just so I could check if it changes after I click and it doesn't. It always remains on 0 that's why the message appears after you click but what it's supposed to do is calculate the distance between the agent and the hit.point and then when it's within .1f range the message appears.