Hi guys,
I am having a problem in ScreenToWorldPoint conversion and I cannot figure out the problem. Here is the problem.
I have a cube in the scene in the position of -21.59, 1.28, -95.24 Rotation -90.00 in the Y axis. I want to get the cube position in the word space when I click on the object. The idea is I want to get the position of the cube when the screen coordinates are given.
This is the script
public class CoordinatesConverter : MonoBehaviour {
public GameObject CCTVcamera;
private Camera currCamera;
void Start () {
currCamera = CCTVcamera.GetComponent<Camera> () as Camera;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Vector3 mousePosFar = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, currCamera.farClipPlane);
Vector3 mousePosNear = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, currCamera.nearClipPlane);
Vector3 mousePosF = currCamera.ScreenToWorldPoint (mousePosFar);
Vector3 mousePosN = currCamera.ScreenToWorldPoint (mousePosNear);
Debug.DrawRay (mousePosN,mousePosF-mousePosN,Color.green);
print ("mouse xy " + Input.mousePosition.x + " #### " + Input.mousePosition.y);
print ("world xyz " + mousePosN.x + " $$ " + mousePosN.y + " $$ " + mousePosN.z);
}
}
}
The problem is the word xyz values are not correct. y and z values are somewhat correct but the x value various when I move the camera. I think the problem is with z-depth value. I am using currCamera.nearClipPlane . What I found is when I go close to the cube and click on it, it gives almost correct position for the cube. When I go far away from the cube it gives wrong x value. Need some help to figure out the problem. ![]()
Basically speaking I want to get the position of the object when I give the screen coordinates. Below is a picture of my scene.
