x


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.

more ▼

asked May 17 '10 at 06:17 PM

didibus gravatar image

didibus
35 3 3 7

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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

answered May 17 '10 at 06:28 PM

Ashkan_gc gravatar image

Ashkan_gc
9.3k 33 56 120

This made the trick, thanx.

temp.z = cube.transform.position.z- mainCamera.transform.position.z;

May 17 '10 at 07:01 PM didibus

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 :)

May 18 '10 at 05:03 AM Ashkan_gc

is there a way to make the mouse follow the object ?

Nov 05 '11 at 02:10 PM Babilinski

Thanks very much for this! :)

Oct 28 '12 at 11:34 PM tonydincau
(comments are locked)
10|3000 characters needed characters left

this does not work

more ▼

answered Mar 21 at 10:26 AM

dashmasterful gravatar image

dashmasterful
0

please make an new question or comment and not an answer

Mar 21 at 10:38 AM sdgd
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1332
x1001
x223

asked: May 17 '10 at 06:17 PM

Seen: 4714 times

Last Updated: Mar 21 at 10:38 AM