- Home /
check if agent reach destination
I want to check if agent position reach destination. i already checked with Debug.Log, the result is (tagent.position.x==dest1.position.x && tagent.position.z==dest1.position.z) both already has the same value (see pic below, 3rd and 4th log) but "REACHED" wasn't shown on console, please help!
private NavMeshAgent agent;
public Transform dest1, dest2, tagent;
void Start () {
agent = GetComponent<NavMeshAgent> ();
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
if (hit.collider.tag == "group1") {
agent.SetDestination (dest1.position);
Debug.Log ("dest "+dest1.position);
Debug.Log ("tagent"+tagent.position);
if(tagent.position.x==dest1.position.x && tagent.position.z==dest1.position.z)
Debug.Log ("REACHED");
}
}
}
}
Answer by jgodfrey · Apr 07, 2016 at 06:48 PM
First, if I understand your statement and your image, the 3rd and 4th messages do not reflect the same position because the Y values are different. Oh, wait, I see you don't care about the Y value in your code, so ignore that... ;)
Second, attempting to compare floating point values for equality is a recipe for disaster. Instead of determining if 2 floating point values are exactly equal, you should see if they are "close enough". You can do that any number of ways, but here's a simple method:
float closeEnough = 0.005;
if (Mathf.Abs(tangent.position.x - dest1.position.x) <= closeEnough && Mathf.Abs(tangent.position.z - dest1.position.z) <= closeEnough
{
// the positions are within "closeEnough" distance
}
Your answer
Follow this Question
Related Questions
When a gameobject is destroyed a chunk of the navmesh gets destroyed 2 Answers
Need help with navmesh,Already bake Navmesh but still got error 1 Answer
Navh Mesh Agents teleporting to spot instead of staying on Nav Mesh 1 Answer
Access navmeshagent calculation data? 0 Answers
Navmesh carving causing issues upon enabling navmesh agent component 0 Answers