はじめに
- Unity + NGUI でスワイプしたときに処理を実行するスクリプトを実装したメモ。
- スワイプ終了時と、上下左右のスワイプにそれぞれひもづけて、実行するメソッドを登録できる。
スワイプしたときに処理を実行するスクリプト
- Collider のアタッチされた任意の GameObject にアタッチし、インスペクターから実行するメソッドを登録すると、その GameObject がスワイプされたときに処理が呼び出される。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SwipeTrigger : MonoBehaviour {
static public SwipeTrigger current;
public List<EventDelegate> onSwipeEnd = new List<EventDelegate> ();
public List<EventDelegate> onSwipeUp = new List<EventDelegate> ();
public List<EventDelegate> onSwipeDown = new List<EventDelegate> ();
public List<EventDelegate> onSwipeLeft = new List<EventDelegate> ();
public List<EventDelegate> onSwipeRight = new List<EventDelegate> ();
public Vector2 total;
void OnDragStart () {
total = Vector2.zero;
}
void OnDrag (Vector2 delta) {
total += delta;
}
void OnDragEnd () {
float angle = Vector2.Angle (Vector2.up, total);
current = this;
if (angle <= 45) {
EventDelegate.Execute (onSwipeUp);
} else if (45 < angle && angle <= 135) {
if (total.x < 0) {
EventDelegate.Execute (onSwipeLeft);
} else {
EventDelegate.Execute (onSwipeRight);
}
} else {
EventDelegate.Execute (onSwipeDown);
}
EventDelegate.Execute (onSwipeEnd);
current = null;
}
}
ひもづけられるスクリプトの実装例
- このスクリプトをアタッチした GameObject を SwipeTrigger の onSwipeEnd などにドラッグアンドドロップで登録して使用する。
- SwipeTrigger.current にはメソッド呼び出し元のオブジェクトが一時的に格納されるので、current.total でスワイプ時の移動量である Vector2 が取得できる。
using UnityEngine;
using System.Collections;
public class SwipeListener : MonoBehaviour {
public void OnSwipeUp () {
Debug.Log ("call swipe up");
Debug.Log (SwipeTrigger.current.total);
}
public void OnSwipeDown () {
Debug.Log ("call swipe down");
Debug.Log (SwipeTrigger.current.total);
}
public void OnSwipeLeft () {
Debug.Log ("call swipe left");
Debug.Log (SwipeTrigger.current.total);
}
public void OnSwipeRight () {
Debug.Log ("call swipe right");
Debug.Log (SwipeTrigger.current.total);
}
public void OnSwipeEnd () {
Debug.Log ("call swipe end");
Debug.Log (SwipeTrigger.current.total);
}
}