1、首先我们先定义一个枚举,用来表示手势滑动的四个方向:
<span style="font-size:14px;">public enum TouchDirection { Unkown, Left, Right, Up, Down }</span>
2、定义类:TouchInput
<span style="font-size:14px;">public class TouchInput : MonoBehaviour { public static TouchInput instance; private Vector2 touchBeginPos; private Vector2 touchEndPos; } </span>
3、对instance进行初始化:
<span style="font-size:14px;">void Start () { Init(); } void Init() { if (instance == null) { instance = this; } }</span>
4、编写根据Touch计算滑动方向:
<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>
5、使用方法:
首先,我们必须把我们写好的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; } }
这样不论在什么地方,只要我们需要,我们就可以实例TouchInput.instance,进而拿到我们的滑动方向。
时间: 2024-10-12 12:40:24