- Home /
Get mouse position relative to camera
Hello,
I have a simple game where I am applying force to an object depending on where the mouse is when clicked. The problem I'm running into is that the worldpoint is a static thing so as soon as the camera moves this code (below) stops working.
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rb.AddForce(mousePos * strength, ForceMode2D.Impulse);
I tried ScreenToViewportPoint but this doesn't work because I need the central point to be 0,0 in order to get the correct coordinates relative to the center of the screen.
Any thoughts how how I can keep this working as the camera moves around?
Thanks
Answer by AbdeCodeEnjoyer · Oct 20, 2021 at 04:12 AM
Make mousePos a unitary vector (x,y = 1)
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition).normalized;
if your problem was that your object was jumping higher if the camera went right or up then this should fix it.
Ah, sorry the problem is that the WorldPoint itself is based on a set point in the world so the mouseposition used in this code will always be based on that position regardless of where the camera is.
So as you move it stops working. Say you move to the right, now you are unable to move left again because anywhere you click is to the right of the 0,0 point even if its to the left of the current camera position.
I'm looking for a way to deter$$anonymous$$e these same coordinates but based on the center of the camera as 0,0 instead of the center of the world.
Answer by btunick26 · Oct 21, 2021 at 01:30 AM
found a solution:
Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
Vector3 direction = (Vector3)(Input.mousePosition - screenPoint);
direction.Normalize();
rb.AddForce(direction * strength, ForceMode2D.Impulse);
Your answer