Unity實現簡單手勢識別
阿新 • • 發佈:2020-07-13
本文例項為大家分享了Unity實現手勢識別的具體程式碼,供大家參考,具體內容如下
程式碼很簡單沒有難度,都有註解,隨便看一看 就會了。
CallEvent () 方法需要自己搭載使用。
Unity程式碼
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 手勢識別 /// </summary> public class PlayerAnimator_ZH : MonoBehaviour { //滑鼠第一次點選位置 public Vector2 _MousePos; //位置列舉 public GestureState _GestureStateBe; //最小動作距離 private float _MinGestureDistance = 20.0f; //手勢開啟布林 private bool _IsInvaild; void Update() { //手勢方法 GestureOnClick(); } //手勢方法 public void GestureOnClick() { //手勢為空 _GestureStateBe = GestureState.Null; if (Input.GetMouseButtonDown(0)) { //第一次滑鼠點選位置記錄 _MousePos = Input.mousePosition; //開啟手勢識別 _IsInvaild = true; } if (Input.GetMouseButton(0)) { //滑鼠軌跡向量 Vector2 _Dis = (Vector2)Input.mousePosition - _MousePos; //畫線 Debug.DrawLine(_MousePos,(Vector2)Input.mousePosition,Color.cyan); //判斷當前 向量的長度 是否大於 最小動作距離 if (_Dis.magnitude>_MinGestureDistance) { //判斷在 空間 X軸 還是在 Y軸 if (Mathf.Abs(_Dis.x) > Mathf.Abs(_Dis.y) && _IsInvaild) { if (_Dis.x > 0) { //如果當前向量值 X 大於 0 就是 Right 狀態 _GestureStateBe = GestureState.Right; } else if (_Dis.x < 0) { //如果當前向量值 X 小於 0 就是 Lift 狀態 _GestureStateBe = GestureState.Lift; } } //判斷在 空間 X軸 還是在 Y軸 else if (Mathf.Abs(_Dis.x) < Mathf.Abs(_Dis.y) && _IsInvaild) { if (_Dis.y > 0) { //如果當前向量值 Y 大於 0 就是 Up 狀態 _GestureStateBe = GestureState.Up; } else if (_Dis.y < 0) { //如果當前向量值 Y 小於 0 就是 Down 狀態 _GestureStateBe = GestureState.Down; } } //關閉手勢識別 _IsInvaild = false; } } } //呼叫事件 public void CallEvent() { switch (_GestureStateBe) { case GestureState.Null: // Null 方法呼叫(自己寫) break; case GestureState.Up: // Up 方法呼叫(自己寫) break; case GestureState.Down: // Down 方法呼叫(自己寫) break; case GestureState.Lift: // Lift 方法呼叫(自己寫) break; case GestureState.Right: // Right 方法呼叫(自己寫) break; default: break; } } //狀態列舉 public enum GestureState { Null,Up,Down,Lift,Right } }
其實程式碼還可進行補充,比如左上、左下、右上、右下、疊加等等吧,如有問題就 Call 我吧。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。