ScreenToWorldPoint offset for different resolutions in Unity 2D

1.4k views Asked by At

I'm developing a 2D game and I need to be able to detect the mouse position in the game world. The thing is, when I'm on the editor it works just fine, but when I run the standalone and set a resolution with an aspect ratio different from the native one on my computer, it has a weird offset.

Click offset

In the picture, the red dot represents the position of my mouse when I click, and the yellow dot represents where the game detects the position. I don't have this problem when I run the fullscreen with an aspect ratio 16:9, which is my PC's default.

The code for the detection is the following.

void useHook(Vector3 mousePosition)
{
    Vector2 mousePos = new Vector2(mousePosition.x, mousePosition.y);

    Vector2 ray2D = Camera.main.ScreenToWorldPoint(mousePos);
    RaycastHit2D hit = Physics2D.Raycast(ray2D, Vector2.zero);
    if (hit.collider != null)
    {
        GameObject target = hit.collider.gameObject;
        if (target.tag.Equals("Grappleable"))
        {
            //Grapple
        }
    }
}

I'm using an ortho camera and calling useHook like this.

Update()
{
    if(Input.GetKeyDown(KeyCode.Mouse0))
    {
        useHook(Input.mousePosition);
    }
}
0

There are 0 answers