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.

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);
}