Mouse Position Values are Tiny
Hi all, I want to get my mouse position, but when I get it, it comes out a fraction of what it should be:
Vector3 mouseScreenPos = Input.mousePosition;
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(new Vector3(mouseScreenPos.x, mouseScreenPos.y, Camera.main.nearClipPlane));
Vector3 mousePos = new Vector3(mouseWorldPos.x, transform.position.y, mouseWorldPos.z);
I logged my mouse position and it seems to be working, but at an extremely incremental amount. For example if the mouse is at x = 6, it would tell me it's at x = 0.2. Thanks in advance, here's a gif of my problems (you can see everything logged in my console to the right, I have 3 different debug logs): Click here
Answer by streeetwalker · Apr 21, 2020 at 07:43 AM
@harperrhett, You're getting a world point at the near clipping plane. Of course those values are smaller the closer the near clipping plane is to the camera because it the the size of the clipping plane depends on its distance from the camera and your view angle. Use a larger z value.
Perhaps you are unclear about what ScreenToWorldPoint does?
It does not return a point on an object that the mouse is over. You need a RayCast to do that using any ScreenToWorldPoint at one end (no matter what z distance you use to calculate it) and the camera as the origin. Cast a ray outward using those two points and get the object hit to find the World position of the hit point "under" the mouse.
ScreenToWorldPoint delivers a World point on a plane perpendicular to the Camera's Z axis at the z distance you specify. The close that plane is to the camera, the smaller the World Point numbers returned.
Thanks! I guess I didn't really understand what the near clipping plane does. I replaced near clipping plane with Camera.main.transform.position.y, which got its depth, and that seemed to work perfectly!
Here's what my final bit of code looks like for anyone else struggling (in my player controller):
Vector3 mouseScreenPos = Input.mousePosition;
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(new Vector3(mouseScreenPos.x, mouseScreenPos.y, Camera.main.transform.position.y));
Vector3 mousePos = new Vector3(mouseWorldPos.x, transform.position.y, mouseWorldPos.z);
It needs a little bit of cleaning up, I think I can bring it down to two lines, but it works :)
Your answer
Follow this Question
Related Questions
Create a prefab object into the scene exactly where the mouse is pointing 2 Answers
Mouse Cursor is flashing 0 Answers
Play sound (OnMouseOver) 2 Answers
Rotate car wheels with mouse position and not arrow keys 0 Answers
How do I make my player look and make my bullet move at direction of my mouse 1 Answer