1、首先我们先定义一个枚举,用来表示手势滑动的四个方向:
<span style="font-size:14px;">public enum TouchDirection { Unkown, Left, Right, Up, Down }</span>
<span style="font-size:14px;">public class TouchInput : MonoBehaviour { public static TouchInput instance; private Vector2 touchBeginPos; private Vector2 touchEndPos; } </span>
<span style="font-size:14px;">void Start () { Init(); } void Init() { if (instance == null) { instance = this; } }</span>
<span style="font-size:14px;">public TouchDirection GetTouchMoveDirection() { if (Input.touchCount > 0) { TouchDirection dir = TouchDirection.Unkown; if (Input.touches[0].phase != TouchPhase.Canceled) { switch (Input.touches[0].phase) { case TouchPhase.Began: touchBeginPos = Input.touches[0].position; break; case TouchPhase.Ended: touchEndPos = Input.touches[0].position; if (Mathf.Abs(touchBeginPos.x - touchEndPos.x) > Mathf.Abs(touchBeginPos.y - touchEndPos.y)) { if (touchBeginPos.x > touchEndPos.x) { dir = TouchDirection.Left; } else { dir = TouchDirection.Right; } } else { if (touchBeginPos.y > touchEndPos.y) { dir = TouchDirection.Down; } else { dir = TouchDirection.Up; } } break; } } return dir; } else { return TouchDirection.Unkown; } }</span>
首先,我们必须把我们写好的TouchInput脚本挂在物体上实例,在需要用到的地方应用:
void Update () { TouchInputTest(); } void TouchInputTest() { switch (TouchInput.instance.GetTouchMoveDirection()) { case TouchDirection.Up: Debug.Log("Up"); break; case TouchDirection.Down: Debug.Log("Down"); break; case TouchDirection.Left: Debug.Log("Left"); break; case TouchDirection.Right: Debug.Log("Right"); break; } }
原文地址:http://blog.csdn.net/u014076894/article/details/45722879