Skip to content

Instantly share code, notes, and snippets.

@asus4
Created February 28, 2012 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asus4/1929944 to your computer and use it in GitHub Desktop.
Save asus4/1929944 to your computer and use it in GitHub Desktop.
delegate Tap, Drag, Swipe
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