Correct way to calculate mouse "z" position (Unity 3d)

Whenever I develop games that use mouse input, I hesitate to calculate the position of the mouse. Especially the z position.

Methods that I have seen in many cases.

  • mouse position z = mouse position y.

  • z = distance between camera and subject.

  • z = difference b / w of object z and camera z. (I am using. Does not work when the camera and object are rotated).

  • z = some arbitrary value. (many use 0 and some other values).

  • others.

Which method is correct? Is there any other method that is correct?

Please let me know.

+3


source to share


3 answers


The same answer as in your second question based on mouse also applies here: Mouse targeting Unity3d



TL; DR: Use a raycast from the camera to traverse the plane where the action is on.

+1


source


Vector3 pz = Camera.main.ScreenToWorldPoint (Input.mousePosition);



pz.z should be what you are asking for if I understand correctly. Tell me if it works.

0


source


The position of the mouse is theoretically external to the game world itself. Therefore, the position of the mouse is simply related to the X and Y coordinates on the screen where you interact with the game (IE width: the height of your game).

What you are asking seems to be more like "How do I simulate the position of the mouse in my game world?"

As Mario pointed out, Camera.main.ScreenToWorldPoint (Input.mousePosition) converts your mouse position to world coordinates. However, this assumes that your main camera is where you want to convert to. What you really want to do is call the ScreenToWorldPoint method on the Camera, which displays the entire space in which you want to interact. For example, you can have your main game world (0, 0, 0), but you can show your GUI from above using a separate camera that displays objects (-5000, 0, 0).

To answer your question, to simulate the z position of the mouse it should just be the same z value as your camera. Then you can perform calculations on this value according to your specific needs.

IE:

1) mouse.position.z = mouse.position.y - They are completely different. Now you just use an arbitrary value 2) Distance between camera and object is a calculation done from the original .position.z object and the original mouse.position.z. Not your actual z-value. 3) See 2.4) See 1.

0


source







All Articles