Raycast mouse position to world position
Hello,
I am creating a dynamic terrain and would like to know the x and z position if I clicked on the terrain or on a game object. I am using a raycast for this:
[code=CSharp] RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(ray.origin, ray.direction * 5000, Color.red, 1000000f); if (Physics.Raycast(ray, out hit, Mathf.Infinity)) { if (hit.transform.gameObject != null) { Debug.Log("HIT " + hit.transform.gameObject.layer + ":" + hit.point.x + ", " + hit.point.y + ", " + hit.point.z + ", " + getRealHeight(hit.point.x, hit.point.z)); } } [/code]
In the two screenshots below you can see the point where I clicked from two perspectives and the last three lines in the log correspond to the Debug.Log line in the code above. Although in this example the x position seems correct, the y position is incorrect (see position of the tank object in the second screen). The DrawLine shows that it should have given the correct values.
Sometimes the values are correct, but other times the x and/or y position is incorrect. I have tried to add the terrain to a seperate layer (25), but still I get incorrect values.
Your answer
Follow this Question
Related Questions
Detect MouseOver/Click for UI Canvas Object 5 Answers
Why is my Physics.Raycast not returning true? 0 Answers
How to perform this Word Game 0 Answers