using UnityEngine;
using System.Collections;
public class TouchEventManager : MonoBehaviour {
public float MinimumSwipeDist;
public float ThresholdAngle;
public delegate void GestureEventHandler();
public static event GestureEventHandler OnSwipeRight;
public static event GestureEventHandler OnSwipeLeft;
public static event GestureEventHandler OnSwipeUp;
public static event GestureEventHandler OnSwipeDown;
private Vector2 mStartPos;
// Update is called once per frame
void Update () {
if (Input.touchCount > 0) {
Touch touch = Input.touches[0];
switch(touch.phase) {
case TouchPhase.Began:
mStartPos = touch.position;
break;
case TouchPhase.Ended:
float swipeDist = (touch.position - mStartPos).magnitude;
// check if legal swipe
if(swipeDist > MinimumSwipeDist) {
determineSwipeType(touch.position);
}
break;
}
}
}
void determineSwipeType(Vector2 endPosition) {
float angle = Vector2.Angle (Vector2.right, (endPosition - mStartPos));
if (angle < ThresholdAngle) {
// right swipe
if(OnSwipeRight != null) {
OnSwipeRight();
}
} else if(angle >= ThresholdAngle && angle <= 180 - ThresholdAngle) {
float swipeValue = Mathf.Sign(endPosition.y - mStartPos.y);
if(swipeValue > 0) {
// up swipe
if(OnSwipeUp != null) {
OnSwipeUp();
}
} else {
// down swipe
if(OnSwipeDown != null) {
OnSwipeDown();
}
}
} else if(angle >= 180 - ThresholdAngle){
// left swipe
if(OnSwipeLeft != null) {
OnSwipeLeft();
}
}
}
}
I have the above code to detect swipe gesture in my game. I recently implemented some UI using the new UI system introduced in v4.6. I have a pause/resume button during gameplay and when I click on the buttons and make a small swipe motion while clicking, my swipe gesture code registers it and affects the gameplay. I have read, that I can do a raycast in my swipe gesture code to check if the touch hits any UI elements and if so not consider it as a swipe but I wanted to know if thats the standard way of doing it or I can somehow block events to my swipe code. I use Input.Touches in my swipe recognition which makes me believe that I will always have the touches in there even on UI buttons and might have to do some custom checking. If anyone knows of a better solution let me know. Also, feel free to use this code for your projects if anyone wants to. Thank you.