- Home /
Have a gameObject follow the mouse in sync. So that the mouse pointer is always over the object.
Hi,
I have a very simple scene that contains a cube. I want to be able to drag the cube around with the mouse, in a way that syncs perfectly with the mouse. The mouse cursor should always remain over the object, and visually, the object should move as much as the mouse did.
Here's the code I have now:
xx = Input.mousePosition.x; yy = Input.mousePosition.y;
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(xx, yy, cube.transform.position.z));
cube.transform.Translate((pos.x - camera.transform.position.x), (pos.y - camera.transform.position.y), 0);
This works fine when I put the camera in Orthographic mode. So I'm guesing the problem is the perspective isn't taken into account. I should have my cube move more when it is far, and move less when it is close, so that its always in sync with the mouse, but I don't know how to do it.
Thank you.
Answer by Ashkan_gc · May 17, 2010 at 06:28 PM
the third argument of ScreenToWorldPoint is the distance between camera and the cube. also in last line you can set the
cube.transform.position = pos;
i have a code that i am sure that it works
while (Input.GetMouseButton(0))
{
temp = Input.mousePosition;
temp.z = cube.transform.position.z- mainCamera.transform.position.z;
transform.position = mainCamera.ScreenToWorldPoint(temp);
}
This made the trick, thanx.
temp.z = cube.transform.position.z- mainCamera.transform.position.z;
yes it's the trick. as the documentation says z argument should be the distance from the camera but i don't know why people don't read it well. i myself had problem realizing it for some hours. i set this to 0 and my code did not work. i read the docs again and said oops :)
Your answer
