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");
}
}
}