PolygonCollider2D seems not working with raycasting

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            Debug.Log(hit.collider);
            if (hit.collider != null)
            {
                Debug.Log(hit.collider.gameObject.name);
            }
        }
    }

The context is a standard polygon collider (+ mesh filter/renderer). It prints null always unless I set direction to up (then it returns collider’s name ALWAYS no matter where you click). The camera is Z = -10, the object is at zero. Also I have a canvas under object.

If anyone was experiencing this issue, after careful debugging i found out that Camera.ScreenToWorldPoint receives z as depth while Input.mousePosition gives 0 always. So it was quite easy to fix;

            Vector3 mouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mouse), v);
2 Likes