- Home /
Input.mouseposition affected by game scene size
I am trying to position a sprite based off of mouse position. My code:
void Update ()
{
X = Input.mousePosition.x;
Y = Input.mousePosition.y;
follow.transform.position = new Vector2 (X, Y);
}
"follow" is a public Game Object defined earlier in the code. The code functions almost as expected, except that if I re-size the Game Scene, follow's center is no longer positioned at the cursor's position.
At default 16:9 aspect game scene view:
At 16:9 aspect game scene view that is resized:
I'm relatively new to unity so I'm no expert. I'm guessing that this issue is due to the follow sprite being automatically re-sized based off of the game scene while the mouse-position reference is unaffected by the screen size. Any help would be greatly appreciated, thanks.
Answer by Eno-Khaon · Jun 22, 2015 at 07:51 PM
Input.mousePosition returns "The current mouse position in pixel coordinates. (Read Only)". As @maccabbe stated, what you'll want to use is Camera.ScreenToWorldPoint in order to transform that position into a location in your game world.
void Update()
{
Vector3 worldMousePos = Camera.Main.ScreenToWorldPoint(Input.MousePosition);
follow.transform.position = new Vector2(worldMousePos.x, worldMousePos.y);
}
Answer by chrismkhill · Jun 22, 2015 at 08:53 PM
Hey there,
Input.mousePosition is "The current mouse position in pixel coordinates"
Try instead this which will convert it to world coordinates.
X = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;