用過Unity的都知道自帶的Input.touches並不支持鼠標輸入,給咱們的調試帶來很大的不方便。那麼咱們會發現其實有不少觸控方面的插件,如inputtouches,easy touch,fingerGesture等。this
下面我主要講解FingerGesture的使用,這個插件不是免費的,能夠自行購買spa
1.導入插件插件
導入後的插件會在Assets/Plugins下面調試
2.拖動Assets/Plugins/FingerGestures/Prefabs/FingerGestures到你的Hierarchy中,以下圖code
3.建立空節點GestureObj,而後綁定腳本TestGesture.csorm
using UnityEngine; using System.Collections; public class testGestures : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // 單擊 void OnTap(TapGesture gesture) { if (gesture.Selection == tapObject) { Debug.Log("Tab!!!!!!!!!!!"); } } // 雙擊 void OnDoubleTap(TapGesture gesture) { if (gesture.Selection == doubleTapObject) { Debug.Log("Double Tab!!!!!!!!!!!"); } } void OnSwipe(SwipeGesture gesture) { // make sure we started the swipe gesture on our swipe object // we use the object the swipe started on, instead of the current one GameObject selection = gesture.StartSelection; if (selection == swipeObject) { Debug.Log("Swipe!!!!!!!"); } } int dragFingerIndex = -1; void OnDrag(DragGesture gesture) { // 獲取起始點 FingerGestures.Finger finger = gesture.Fingers[0]; if (gesture.Phase == ContinuousGesturePhase.Started) { // dismiss this event if we're not interacting with our drag object if (gesture.Selection != dragObject) return; // remember which finger is dragging dragObject dragFingerIndex = finger.Index; } else if (finger.Index == dragFingerIndex) // gesture in progress, make sure that this event comes from the finger that is dragging our dragObject { if (gesture.Phase == ContinuousGesturePhase.Updated) { // update the position by converting the current screen position of the finger to a world position on the Z = 0 plane dragObject.transform.position = GetWorldPos(gesture.Position); } else { // reset our drag finger index dragFingerIndex = -1; } } } // 長按 void OnLongPress(LongPressGesture gesture) { if (gesture.Selection == longPressObject) { Debug.Log("Long press!!!!!!"); } } // 定義變量,用來操做 public GameObject longPressObject; public GameObject tapObject; public GameObject doubleTapObject; public GameObject swipeObject; public GameObject dragObject; // 公共方法 public static Vector3 GetWorldPos(Vector2 screenPos) { Ray ray = Camera.main.ScreenPointToRay(screenPos); // we solve for intersection with z = 0 plane float t = -ray.origin.z / ray.direction.z; return ray.GetPoint(t); } }
4.添加指定的觸控對象對象
5.添加Component
blog
6.添加Screen Raycasterip
7.要爲對象添加2D物理碰撞區域。否則的話點擊沒有效果。rem