- Home /
mouse position seems to be the same everytime
I have read the many posts about ScreenToWorldPoint which got me this far..
What I want to do is move an item left if I click the left side of it, and right if I click the right of it.
My first hurdle seems to be getting the position of the mouse anyway.. with the following, anywhere I click on the game object, I get the EXACT same coordinates...
I am sure its a simple screw up, but any advice would be gratefully received.
N
#pragma strict
var movewhat : Transform;
function OnMouseUp ()
{
movewhat.position.x = (Camera.main.ScreenToWorldPoint(Input.mousePosition)).x;
Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
You could find the pixel position of the mouse then cast a ray out to the object:
http://docs.unity3d.com/Documentation/ScriptReference/Input-mousePosition.html
Answer by robertbu · Jul 19, 2013 at 03:48 PM
Mouse position is a screen coordinate which is 2D. A world coordinate is 3D. In order to make the conversion you have to specify the distance in front of the camera as the 'Z' value in the Vector3 you pass to ScreenToWorldPoint(). This is easy if the camera looks down one of the axes. Assuming your camera is looking towards positive 'Z' (i.e. rotation (0,0,0)), you could do:
var dist = movewhat.position.z - Camera.main.transform.position.z;
var v3Pos = Vector3(Input.mousePosition.x Input.mousePosition.y, dist);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
movewhat.position.x = v3Pos.x;