- Home /
getting world coordinates of mouse position
There are many questions like this, but none resolve my current problem. I'm trying to use the mouse position to set the position of the object I'm clicking in. For example, if I want to drag a box around on the x and y axis. When I use camera.ScreenToWorldPoint it keeps giving me the position of the camera rather than the mouse.
if(Input.GetMouseButton(0)) {
if(Physics.Raycast(ray,out hit,100f)) {
Vector3 mouseWorld = camera.ScreenToWorldPoint(Input.mousePosition);
//Debug.Log (mouseWorld);
if(hit.collider.gameObject.tag == "dragable") {
hit.transform.position = mouseWorld;
}
}
}
Answer by TheDarkVoid · Nov 24, 2012 at 05:07 PM
you need to use Camera.ScreenPointToRay and use the hit info to get the object's position.
I want to SET the position of the object, sorry if that was unclear. I can get the hit info no problem, but I'm trying to set it equal to the mouse position in world coordinates.
Input.mousePosition doesn't give a screen point, you will have to subtract the y from screen.height to get the screen point
what do you mean? Doesn't it return the x and y pixel coordinates?
it return the x,y, but ti does so where y = 0 is the bottom of the screen, while screen point y=0 is the top
So how does ScreenPointToRay(Input.mousePosition) work and ScreenToWorldPoint(Input.mousePosition) doesn't?
Answer by nenorse · Nov 16, 2013 at 10:07 PM
Anycase anyone is interested, I also had the same problem. I managed to resolve it by making sure of three things
The Input.MousePosition.x is reversed (Screen.Width)
The Input.MousePosition.y is reveresed (Screen.Height)
The Z of the Vector is based from the camera position and in my case the z depth of the object that I was looking at (as they were all the same size).
Or..
Vector3 inputPosition = Input.mousePosition; Vector3 ray = Camera.mainCamera.ScreenToWorldPoint(new Vector3(Screen.width - inputPosition.x, Screen.height - inputPosition.y, Camera.main.transform.position.z - 2f));