Screen positions incorrect when using pixel perfect camera

Hi all,

I’m encountering an issue where using my URP pixel perfect camera to map a screen point to a ray is producing incorrect results.

Consider the following code, which uses the Enhanced Touch API to receive a Touch instance.

private bool IsTouchingSelf(Touch touch)
        {
            Ray raycast = Camera.main.ScreenPointToRay(touch.screenPosition);
            Debug.DrawRay(raycast.origin, raycast.direction.normalized * 15, Color.red, 5f);
           
            var hit = Physics2D.Raycast(
                raycast.origin,
                raycast.direction,
                Mathf.Infinity,
                targetLayers);
           
            if ((hit.collider != null ? hit.collider.gameObject : null) == gameObject)
            {
                return true;
            }

            return false;
        }

When running this, the ray is drawn in a location a few units away from where the touch actually occurred. This is in the editor when the game view is in a tab.

If I maximize the game view, it works as expected. Further, if I disable the Pixel Perfect component on the camera, it again works as expected.

Has anybody encountered this? Should I be doing something other than ScreenPointToRay to account for pixel perfect camera modifications?

Thanks!

I encountered same issue:(

I found the reason, the pixel perfect camera’s “Crop Frame” was turned on, which caused the camera’s ViewPort Rect be modified.

        // pointer = inputAction.ReadValue<Vector2>();
        public Vector2 CorrectByRect(Camera camera, Vector2 pointer)
        {
            var size = camera.rect.size;
            var offset = camera.pixelRect.position;
            return new Vector2(pointer.x * size.x + offset.x, pointer.y * size.y + offset.y);
        }