Advertisement
Muk99

SwipeFinger

Feb 5th, 2015
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SwipeFinger : MonoBehaviour {
  5.    
  6.     public enum Directions {Up, Down, Left, Right, None}
  7.  
  8.     [HideInInspector]
  9.     public Directions direction = Directions.None;
  10.     //The min swipe distance to change direction
  11.     public float sensibility = 2.5f;
  12.  
  13.     //Touch latched finger
  14.     private int latchedFinger = -1;
  15.  
  16.     void Update () {
  17.         Vector2 deltaPosition = Vector2.zero;
  18.  
  19.         #if UNITY_EDITOR
  20.         //Get delta position based on mouse move on editor
  21.         if (Input.GetMouseButton (0)) {
  22.             deltaPosition.x = Input.GetAxis ("Mouse X");
  23.             deltaPosition.y = Input.GetAxis ("Mouse Y");
  24.         }
  25.  
  26.         #elif UNITY_STANDALONE_WIN
  27.         //Same here, but for standalone application
  28.         if (Input.GetMouseButton (0)) {
  29.             deltaPosition.x = Input.GetAxis ("Mouse X");
  30.             deltaPosition.y = Input.GetAxis ("Mouse Y");
  31.         }
  32.  
  33.         #else
  34.         //And here gets delta position with touch
  35.         foreach (Touch touch in Input.touches) {
  36.             if (latchedFinger == -1 && touch.phase == TouchPhase.Began)
  37.                 latchedFinger = touch.fingerId;
  38.  
  39.             if (latchedFinger == touch.fingerId &&
  40.                (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled))
  41.                 latchedFinger = -1;
  42.  
  43.             if (touch.fingerId == latchedFinger && touch.phase == TouchPhase.Moved) {
  44.                 deltaPosition = touch.deltaPosition;
  45.             }
  46.         }
  47.         #endif
  48.  
  49.         //Send delta position to a method to check which way finger was swiped
  50.         SetDirection (deltaPosition);
  51.     }
  52.  
  53.     void SetDirection (Vector2 deltaPosition) {
  54.         //Check direction based on delta position
  55.         if (deltaPosition.y > sensibility)
  56.             direction = Directions.Up;
  57.  
  58.         else if (deltaPosition.y < -sensibility)
  59.             direction = Directions.Down;
  60.  
  61.         else if (deltaPosition.x > sensibility)
  62.             direction = Directions.Right;
  63.  
  64.         else if (deltaPosition.x < -sensibility)
  65.             direction = Directions.Left;
  66.  
  67.         else
  68.             direction = Directions.None;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement