Calculating distance is not working
Hello, I am working on a game, but when calculating the distance between the position of a ray cast hit from my camera to a terrain collider, it doesn't seem to work properly. RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 10f) && hit.collider.GetType() == typeof(TerrainCollider)) { Debug.Log("Terrain Hit"); offset = Vector3.Distance(hit.transform.position, Camera.main.transform.position); }
As you can see, I have a float offset, which, at the beginning of a drag (I am pretty sure the rest of the class is not needed) is evaluated to be the distance between the camera and the object being dragged, but now, I need my offset to change when I drag the object. I get a log when I move the cursor near the terrain, however, the dragged object is not moving, and when I Debug.Log offset, it stays the same even when moved around different parts of the terrain. Any help?
Answer by ryanjandriuk · Jun 29, 2018 at 11:11 AM
I found the answer! It turns out that hit.transform.position gets the position of the gameobject the hit lands on! Not the position of the hit itself. Fixed with using hit.point instead of hit.transform.position.