Help with RectTransformUtility.RectangleContainsScreenPoint

I’m trying to come up with a simple way to block touch inputs from happening behind the active canvas.

Currently the code detects the input position, gets the mainCamera, gets the rect transform attached to the gameObject but does not return true if I touch inside the visible canvas area on the screen.

Obviously some of the input data is incorrect or I’m using it wrong but I’m not exactly sure. Any help would be appreciated.

public class TouchWithinRect : MonoBehaviour {
  
    public RectTransform targetRect;
    public Camera gameCamera;
    // Use this for initialization
    void Start () {

        targetRect =  GetComponent<RectTransform>();
      
    }
  
    // Update is called once per frame
    void Update () {
     if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            // Get movement of the finger since last frame
            Vector2 touchPosition = Input.GetTouch(0).position;

            Debug.Log("Touch at "+ touchPosition.ToString());

            Debug.Log("camera is "+gameCamera);

               if (RectTransformUtility.RectangleContainsScreenPoint (targetRect, touchPosition, gameCamera))
               {
       
                Debug.Log("Touch is inside");
            }


           

        }
    }

I just took a quick look at the docs, and they don’t confirm my thought, but for a different RectTransformUtility method, with screen space overlay, you must pass the camera as ‘null’.
You could try that and see if it works :slight_smile:

2 Likes

@methos5k you are awesome. I was struggling a lot, it worked like a charm.