Created
February 28, 2012 05:31
-
-
Save asus4/1929944 to your computer and use it in GitHub Desktop.
delegate Tap, Drag, Swipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
// 3 types delegates | |
public delegate void TapDelegate(); | |
public delegate void DragDelegate(Vector3 vec); | |
public delegate void SwipeDelegate(SwipeDirection direction); | |
public enum SwipeDirection { | |
RIGHT, | |
LEFT, | |
UP, | |
DOWN | |
} | |
/// <summary> | |
/// Listen Tap or Drag or Swipe..... | |
/// </summary> | |
[RequireComponent (typeof (BoxCollider))] | |
public class GestureListener : MonoBehaviour { | |
// public | |
public float dragSensitybity = 10f; | |
public float tapTime = 0.3f; | |
// private | |
private float lastClickTime = 0; | |
private Vector3 lastClickPoint; | |
private TapDelegate tapDelegate = null; | |
private DragDelegate dragDelegate = null; | |
private SwipeDelegate swipeDelegate = null; | |
public void SetTapDelegate(TapDelegate del) { | |
this.tapDelegate = del; | |
} | |
public void SetDragDelegate(DragDelegate del) { | |
this.dragDelegate = del; | |
} | |
public void SetSwipeDelegate(SwipeDelegate del) { | |
this.swipeDelegate = del; | |
} | |
void OnMouseDown() { | |
lastClickTime = Time.time; | |
lastClickPoint = ToughToMouseConverter.GetMousePosition(); | |
} | |
void OnMouseDrag() { | |
float nowTime = Time.time; | |
if(nowTime - lastClickTime > tapTime) { | |
Vector3 mousePoint = ToughToMouseConverter.GetMousePosition(); | |
Vector3 diff = mousePoint - lastClickPoint; | |
if(diff.magnitude > dragSensitybity) { | |
onDrag(diff); | |
} | |
} | |
} | |
void OnMouseUp() { | |
float nowTime = Time.time; | |
if(nowTime - lastClickTime < tapTime) { | |
Vector3 mousePoint = ToughToMouseConverter.GetMousePosition(); | |
Vector3 diff = mousePoint - lastClickPoint; | |
if(diff.magnitude < dragSensitybity) { | |
onTap(); | |
} | |
else { | |
onSwipe(diff); | |
} | |
} | |
} | |
void onTap() { | |
if(tapDelegate != null) { | |
tapDelegate(); | |
} | |
} | |
void onDrag(Vector3 vec) { | |
if(dragDelegate != null) { | |
dragDelegate(vec); | |
} | |
} | |
void onSwipe(Vector3 vec) { | |
SwipeDirection d; | |
// horizontal | |
if(System.Math.Abs(vec.x) > System.Math.Abs(vec.y)) { | |
d = vec.x > 0 ? SwipeDirection.RIGHT : SwipeDirection.LEFT; | |
} | |
// vertical | |
else { | |
d = vec.y > 0 ? SwipeDirection.UP : SwipeDirection.DOWN; | |
} | |
if(swipeDelegate != null) { | |
swipeDelegate(d); | |
} | |
} | |
} | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment