An helper class to handle single tap gesture in 2D games. It uses the raycast mechanism to detect collisions.
using UnityEngine; namespace Assets.Scripts.Framework { public static class TapHelper { /// <summary> /// Get touch position /// </summary> /// <returns>Current touch position</returns> public static Vector3 GetTouchedPosition() { Input.simulateMouseWithTouches = true; if (Input.touchCount > 0 || Input.GetMouseButtonDown(0)) { #if UNITY_EDITOR return Input.mousePosition; #else return Input.touches[0].position; #endif } return Vector3.zero; } /// <summary> /// Return if a game object is touch /// </summary> /// <param name="name">game object name</param> /// <returns>true if touched, otherwise false</returns> public static bool IsGameObjectTouched(string name) { Input.simulateMouseWithTouches = true; if (Input.touchCount > 0 || Input.GetMouseButtonDown(0)) { #if UNITY_EDITOR var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 1f); #else var hit = Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.touches[0].position).origin, Vector2.zero, 1f); #endif if (hit.collider != null) { return hit.collider.name == name; } } return false; } /// <summary> /// Return if a game object is touched /// </summary> /// <param name="objectToDetect">instance of a game object</param> /// <returns>true if touched, otherwise false</returns> public static bool IsGameObjectTouched(GameObject objectToDetect) { Input.simulateMouseWithTouches = true; if (Input.touchCount > 0 || Input.GetMouseButtonDown(0)) { #if UNITY_EDITOR var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 1f); #else var hit = Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.touches[0].position).origin, Vector2.zero, 1f); #endif if (hit.collider != null) { return hit.collider.gameObject == objectToDetect; } } return false; } } }
Leave a Reply