Detecting Touch Inputs within Bounds in Unity
I recently built an ARKit app where taps on various regions of the UI would have different functions. I had defined these regions with RectTransforms in the Unity Editor, and was trying to find a way to detect whether a tap was situated within the bounds of these areas. Because all the tutorials which I found online attempted to use Rects defined programmatically, instead of RectTransforms, which could be more easily manipulated within the GUI editor, I decided to write this short guide. The process, which is fairly simple, is outlined below:
First, you want to get your standard touch (or other screen space) inputs set up. Below is an example that uses touch input:
Then, assuming you have already defined your RectTransforms in the Editor, grab them with GameObject.Find in your Start function, and store them as variables. Be sure to include UnityEngine.UI for relevant RectTransform functions. Your code should now look something like this:
Now for the interesting bit. Unity’s RectTransformUtility class provides a whole bunch of useful methods for working with RectTransforms. We’ll be making use of one of them: RectangleContainsScreenPoint. It does exactly what its name would suggest. It tells you whether a specific RectTransform contains a point on the screen. This method accepts the following parameters: RectTransform rect, Vector2 screenPoint, Camera cam. The Camera is optional. We’ll incorporate it into our code to test whether our touch falls within our predefined boundary. Your code should now look something like this:
Congratulations! You can now determine whether a touch input occurred within specific bounds! Enjoy your new-found knowledge.
As always, if you have any comments, suggestions, or feedback, feel free to shoot me an email at david (at) davidgu.org