- Home /
Can't convert from mouse screen position to world position
Hi guys, I'm making a 2D game and I'd like the player to be able to choose the direction to shoot at. I'm using Input.mousePosition and I know I need to convert it in world position to be able to get a Vector3 to apply to my bullets, so that they are directed to the area selected by the player.
As you can see from this gif ( https://im5.ezgif.com/tmp/ezgif-5-47ebe7678c.gif ), it doesn't work as I expect it to: I'm using OnDrawGizmos() and that white line should be directed towards the mouse cursor. Here is the script I'm using to draw the line
private void OnDrawGizmos()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 0;
Gizmos.DrawLine(transform.position, mainCamera.ScreenToWorldPoint(Input.mousePosition));
}
I know that I should set mousePosition.z to the distance between the camera and the plane, but I don't know how to retrieve it. However, changing the value of mousePosition.z doesn't produce any change.
Can you help me solve this problem, please? Thank you in advance for your help :)
Answer by hectorux · Jul 04, 2018 at 11:50 PM
You could put a collider behind all the screen, and get the hit transform, then you have he world position of your mouse
Answer by Mr_Teels · Jul 05, 2018 at 08:52 AM
https://answers.unity.com/questions/491711/getting-the-position-of-the-mouse-in-2d-space.html
look here ...
Answer by TheMannyzaur · Jul 06, 2018 at 07:23 AM
Try getting the mouse position by doing Camera.main.ScreenToWorldPoint(Input.mousePosition);