RaycastHit not working on terrain

i am using a raycast to move a nave mash agent on a terrain but it will not register the hit on the terrain but it will register hits of objects on the terrain, the terrain has a box collider around it, and it also give the collider.tag as terrain but always sets the position to the Bottom left corner of the terrain no matter where i click any ideas?

this is the method :

    void castRay()
    {
        Debug.Log("draw");
        Ray ray = camera.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y));
        RaycastHit hit = new RaycastHit();
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.red);
        if (Physics.Raycast(ray, out hit, 10000))
        {
            Debug.Log(hit.collider.name);
            float x = hit.transform.position.x;
            float z = hit.transform.position.z;
            Vector3 hitPosition = new Vector3(x, 0.61f, z);
            Debug.Log(hitPosition);
            selectedUnit.GetComponent<NavMeshAgent>().SetDestination(hitPosition);
        }
    }
}

What you’re looking for is “hit.point” not “hit.transform”. The former refers to the impact point from the ray with the object, whereas the latter refers to the transform of the object that was hit. The transform has no information about the raycast- it’s just a component of the terrain.

2 Likes

I think you want hit.point instead of hit.transform.position

    void castRay()
    {
        Debug.Log("draw");
        Ray ray = camera.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y));
        RaycastHit hit = new RaycastHit();
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.red);
        if (Physics.Raycast(ray, out hit, 10000))
        {
            Debug.Log(hit.collider.name);
            float x = hit.point.x;
            float z = hit.point.z;
            Vector3 hitPosition = new Vector3(x, 0.61f, z);
            Debug.Log(hitPosition);
            selectedUnit.GetComponent<NavMeshAgent>().SetDestination(hitPosition);
        }
    }
}
1 Like

You want to use hit.point.x and hit.point.z, not the transform of the object that was hit (which will always be a static position like 0,0 as you’re finding out).

EDIT: LOL :smile:

Too many of us today! :face_with_spiral_eyes:

1 Like

yea thanks guys