Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Swipe in all directions Touch and Mouse

Discussion in 'Scripting' started by Gustav_Bok, Jan 8, 2013.

  1. Gustav_Bok

    Gustav_Bok

    Joined:
    Dec 6, 2012
    Posts:
    35
    Hi Everyone!

    I had trouble finding good information how to get out swipes in different directions, so I fixed one to share to the community!
    Feel free to tweak the "0.5f" number to get the right feel for how narrow you want to detect the swipe.

    This is for ONE touch, you can add several touches by using a foreach and loop through the Input.touches.

    Code is in C#.

    Touch:

    Code (csharp):
    1.  
    2. //inside class
    3. Vector2 firstPressPos;
    4. Vector2 secondPressPos;
    5. Vector2 currentSwipe;
    6.  
    7. public void Swipe()
    8. {
    9.      if(Input.touches.Length > 0)
    10.      {
    11.          Touch t = Input.GetTouch(0);
    12.          if(t.phase == TouchPhase.Began)
    13.          {
    14.               //save began touch 2d point
    15.              firstPressPos = new Vector2(t.position.x,t.position.y);
    16.          }
    17.          if(t.phase == TouchPhase.Ended)
    18.          {
    19.               //save ended touch 2d point
    20.              secondPressPos = new Vector2(t.position.x,t.position.y);
    21.                            
    22.               //create vector from the two points
    23.              currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    24.                
    25.              //normalize the 2d vector
    26.              currentSwipe.Normalize();
    27.  
    28.              //swipe upwards
    29.              if(currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
    30.              {
    31.                  Debug.Log("up swipe");
    32.              }
    33.              //swipe down
    34.              if(currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
    35.              {
    36.                  Debug.Log("down swipe");
    37.              }
    38.              //swipe left
    39.              if(currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
    40.              {
    41.                  Debug.Log("left swipe");
    42.              }
    43.              //swipe right
    44.              if(currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
    45.              {
    46.                  Debug.Log("right swipe");
    47.              }
    48.          }
    49.      }
    50. }
    For Mouse left click (0):
    Code (csharp):
    1.  
    2.  
    3. //inside class
    4. Vector2 firstPressPos;
    5. Vector2 secondPressPos;
    6. Vector2 currentSwipe;
    7.  
    8. public void Swipe()
    9. {
    10.      if(Input.GetMouseButtonDown(0))
    11.      {
    12.          //save began touch 2d point
    13.         firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    14.      }
    15.      if(Input.GetMouseButtonUp(0))
    16.      {
    17.             //save ended touch 2d point
    18.         secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
    19.        
    20.             //create vector from the two points
    21.         currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    22.            
    23.         //normalize the 2d vector
    24.         currentSwipe.Normalize();
    25.  
    26.         //swipe upwards
    27.         if(currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
    28.         {
    29.             Debug.Log("up swipe");
    30.         }
    31.         //swipe down
    32.         if(currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
    33.         {
    34.             Debug.Log("down swipe");
    35.         }
    36.         //swipe left
    37.         if(currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
    38.         {
    39.             Debug.Log("left swipe");
    40.         }
    41.         //swipe right
    42.         if(currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
    43.         {
    44.             Debug.Log("right swipe");
    45.         }
    46.     }
    47. }
    48.  
    Cheers!
     
    Last edited: Jan 8, 2013
  2. returnONE

    returnONE

    Joined:
    Feb 11, 2013
    Posts:
    1
    Thank you very much for sharing this.
    Works perfectly.
     
  3. chickaboom

    chickaboom

    Joined:
    Oct 7, 2013
    Posts:
    2
    thank you so much, works like charm :)
     
  4. chrisleathers

    chrisleathers

    Joined:
    Jul 6, 2012
    Posts:
    4
    That's really nice simple code and totally effective.. Thanks!! Only thing I had to figure out, was to put it in Update to get it to work.. I don't even know if that is what you intended, but it does work.
     
  5. saddam751

    saddam751

    Joined:
    Nov 6, 2013
    Posts:
    41
    it's not working on my end....i have set many values in place of 0.5 but when i run project in xcode it does not detectes swipes....Kindly help
     
  6. saddam751

    saddam751

    Joined:
    Nov 6, 2013
    Posts:
    41
    it worked THANKS
     
  7. Taneerian

    Taneerian

    Joined:
    Feb 21, 2013
    Posts:
    2
    Quick Question, does this code only do up, down, left and right or is it literally all directions? Thanks!
     
  8. Brad-Keys

    Brad-Keys

    Joined:
    May 1, 2006
    Posts:
    161
    It only does Up, Down, Left, Right. You could easily modify it to do diagonals though and get 8 directions instead of just 4.
     
  9. Brad-Keys

    Brad-Keys

    Joined:
    May 1, 2006
    Posts:
    161
    Here's a new version that helps prevent taps from counting as swipes. It's also meant to be used externally, such as...

    Code (csharp):
    1.  
    2. if (SwipeManager.swipeDirection == Swipe.Up) {
    3.     // do something...
    4. }
    5.  
    And here is the new script.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public enum Swipe { None, Up, Down, Left, Right };
    5.  
    6. public class SwipeManager : MonoBehaviour
    7. {
    8.     public float minSwipeLength = 200f;
    9.     Vector2 firstPressPos;
    10.     Vector2 secondPressPos;
    11.     Vector2 currentSwipe;
    12.  
    13.     public static Swipe swipeDirection;
    14.  
    15.     void Update ()
    16.     {
    17.         DetectSwipe();
    18.     }
    19.  
    20.     public void DetectSwipe ()
    21.     {
    22.         if (Input.touches.Length > 0) {
    23.              Touch t = Input.GetTouch(0);
    24.  
    25.              if (t.phase == TouchPhase.Began) {
    26.                  firstPressPos = new Vector2(t.position.x, t.position.y);
    27.              }
    28.  
    29.              if (t.phase == TouchPhase.Ended) {
    30.                 secondPressPos = new Vector2(t.position.x, t.position.y);
    31.                 currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    32.            
    33.                 // Make sure it was a legit swipe, not a tap
    34.                 if (currentSwipe.magnitude < minSwipeLength) {
    35.                     swipeDirection = Swipe.None;
    36.                     return;
    37.                 }
    38.            
    39.                 currentSwipe.Normalize();
    40.  
    41.                 // Swipe up
    42.                 if (currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
    43.                     swipeDirection = Swipe.Up;
    44.                 // Swipe down
    45.                 } else if (currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
    46.                     swipeDirection = Swipe.Down;
    47.                 // Swipe left
    48.                 } else if (currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
    49.                     swipeDirection = Swipe.Left;
    50.                 // Swipe right
    51.                 } else if (currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
    52.                     swipeDirection = Swipe.Right;
    53.                 }
    54.              }
    55.         } else {
    56.             swipeDirection = Swipe.None;
    57.         }
    58.     }
    59. }
    60.  
    EDIT August 9, 2016:
    New version here
    http://forum.unity3d.com/threads/swipe-in-all-directions-touch-and-mouse.165416/page-2#post-2741253
     
    Last edited: Aug 9, 2016
    aneeshjose likes this.
  10. tryonn

    tryonn

    Joined:
    Feb 4, 2014
    Posts:
    1
    Hello I added this code in my project in debugger mode works as usual, most there when I generate the apk nothing works. help please.
     
  11. tapticc

    tapticc

    Joined:
    Jan 16, 2014
    Posts:
    365
    Perfectly simple, a basic touch evaluation script which just "works", thanks dude!

    P.S. here is a version with 8 directional input with debug info, I am lazy and would have copied somebody else's 8-way script so I'm sure this will be useful lol just add a GUIText object to the screen and point the public debugInfo property to the GUIText object for debug info to check it works:

    using UnityEngine;

    public class SwipeManager : MonoBehaviour
    {
    public enum Swipe { Up, Down, Left, Right, None, UpLeft, UpRight, DownLeft, DownRight };
    public float minSwipeLength = 200f;
    public GUIText debugInfo;

    Vector2 firstPressPos;
    Vector2 secondPressPos;
    Vector2 currentSwipe;

    float tweakFactor = 0.5f;

    public static Swipe swipeDirection;


    void Update ()
    {
    DetectSwipe();
    }

    public void DetectSwipe ()
    {
    if (Input.touches.Length > 0) {
    Touch t = Input.GetTouch(0);

    if (t.phase == TouchPhase.Began) {
    firstPressPos = new Vector2(t.position.x, t.position.y);
    }

    if (t.phase == TouchPhase.Ended) {
    secondPressPos = new Vector2(t.position.x, t.position.y);
    currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);

    // Make sure it was a legit swipe, not a tap
    if (currentSwipe.magnitude < minSwipeLength) {
    debugInfo.text = "Tapped";
    swipeDirection = Swipe.None;
    return;
    }

    currentSwipe.Normalize();

    debugInfo.text = currentSwipe.x.ToString() + " " + currentSwipe.y.ToString();

    // Swipe up
    if (currentSwipe.y > 0 currentSwipe.x > 0 - tweakFactor currentSwipe.x < tweakFactor) {
    swipeDirection = Swipe.Up;
    debugInfo.text = "Up swipe";

    // Swipe down
    } else if (currentSwipe.y < 0 currentSwipe.x > 0 - tweakFactor currentSwipe.x < tweakFactor) {
    swipeDirection = Swipe.Down;
    debugInfo.text = "Down swipe";

    // Swipe left
    } else if (currentSwipe.x < 0 currentSwipe.y > 0 - tweakFactor currentSwipe.y < tweakFactor) {
    swipeDirection = Swipe.Left;
    debugInfo.text = "Left swipe";

    // Swipe right
    } else if (currentSwipe.x > 0 currentSwipe.y > 0 - tweakFactor currentSwipe.y < tweakFactor) {
    swipeDirection = Swipe.Right;
    debugInfo.text = "Right swipe";

    // Swipe up left
    } else if (currentSwipe.y > 0 currentSwipe.x < 0 ) {
    swipeDirection = Swipe.UpLeft;
    debugInfo.text = "Up Left swipe";

    // Swipe up right
    } else if (currentSwipe.y > 0 currentSwipe.x > 0 ) {
    swipeDirection = Swipe.UpRight;
    debugInfo.text = "Up Right swipe";

    // Swipe down left
    } else if (currentSwipe.y < 0 currentSwipe.x < 0 ) {
    swipeDirection = Swipe.DownLeft;
    debugInfo.text = "Down Left swipe";

    // Swipe down right
    } else if (currentSwipe.y < 0 currentSwipe.x > 0 ) {
    swipeDirection = Swipe.DownRight;
    debugInfo.text = "Down Right swipe";
    }
    }
    } else {
    swipeDirection = Swipe.None;
    //debugInfo.text = "No swipe"; // if you display this, you will lose the debug text when you stop swiping
    }
    }
    }
     
    Last edited: Mar 8, 2014
    spencerz likes this.
  12. Amaresh

    Amaresh

    Joined:
    Jan 22, 2014
    Posts:
    21
    When I use the above three lines in another script. It always detects Swipe Up. How to solve this?
     
  13. Amaresh

    Amaresh

    Joined:
    Jan 22, 2014
    Posts:
    21

    @BradKeys When I use the above three lines in another script. It always detects Swipe Up. How to solve this?
     
  14. Brad-Keys

    Brad-Keys

    Joined:
    May 1, 2006
    Posts:
    161
    Try changing SwipeManager line 5 to be...

    Code (csharp):
    1.  
    2. public enum Swipe { None, Up, Down, Left, Right };
    3.  
    It is defaulting to Swipe.Up, but this should make it default to Swipe.None.
     
  15. Amaresh

    Amaresh

    Joined:
    Jan 22, 2014
    Posts:
    21
    Now, it is not recognising any swipe at all.
     
  16. Brad-Keys

    Brad-Keys

    Joined:
    May 1, 2006
    Posts:
    161
    Make sure the script is attached to a GameObject in your scene. And it will only work when you're testing on a mobile device. Good luck.
     
  17. sootie8

    sootie8

    Joined:
    Mar 25, 2014
    Posts:
    233
    Why not use touch.delta position, that way you can iterate through multiple touches.
     
  18. Brad-Keys

    Brad-Keys

    Joined:
    May 1, 2006
    Posts:
    161
    I'm unsure about the original poster, but for my project I wanted the script to only work for a single touch. It could be beefed up more to take more touches into consideration and perhaps you could specify how many you want to care about. But I don't need that sort of complexity.
     
  19. tantorrrr

    tantorrrr

    Joined:
    Jun 4, 2014
    Posts:
    1
    it works perfectly, thanks so much <3
     
  20. sootie8

    sootie8

    Joined:
    Mar 25, 2014
    Posts:
    233
    Then just use input.getTouch[0]
     
  21. RamilOdabaca

    RamilOdabaca

    Joined:
    Jun 28, 2013
    Posts:
    3
    sir im having this errors i dont know why,, what should i do, sorry, im a newbie
     

    Attached Files:

  22. franky9319

    franky9319

    Joined:
    Jul 14, 2014
    Posts:
    1
    it worked. Thank you very much! :D
     
  23. RamilOdabaca

    RamilOdabaca

    Joined:
    Jun 28, 2013
    Posts:
    3
  24. ThesisProblem_12

    ThesisProblem_12

    Joined:
    Jul 4, 2014
    Posts:
    3
    Help me. i have the same problem with ramil odabaca. can anyone teach me how it works.. im newbie too
     
  25. ThesisProblem_12

    ThesisProblem_12

    Joined:
    Jul 4, 2014
    Posts:
    3
    i have the same problem with ramil odabaca,, can anyone teach me how it works? i am newbie.. please need a response asap, :(
     
  26. ThesisProblem_12

    ThesisProblem_12

    Joined:
    Jul 4, 2014
    Posts:
    3
    sir can u teach me how it works? ? i have problems encountered. same error with the other guy who posted on his problem .. hope u can help me too.. thanks in advance.
     
  27. sohaibkhan56

    sohaibkhan56

    Joined:
    Jul 25, 2014
    Posts:
    1
    using UnityEngine;
    using System.Collections;

    public class SwipeSimpleCS1 : MonoBehaviour {

    //public Transform player; // Drag your player here
    private Vector2 fp; // first finger position
    private Vector2 lp; // last finger position
    private float angle;
    private float swipeDistanceX;
    private float swipeDistanceY;





    public float moveSpeed = 6.0f;
    public float jumpSpeed = 5.0f;

    private bool canJump = true;
    private bool[] swipe = new bool[4];

    void Update () {
    foreach(Touch touch in Input.touches)
    {
    if (touch.phase == TouchPhase.Began)
    {
    fp = touch.position;
    lp = touch.position;
    }
    if (touch.phase == TouchPhase.Moved )
    {
    lp = touch.position;
    swipeDistanceX = Mathf.Abs((lp.x-fp.x));
    swipeDistanceY = Mathf.Abs((lp.y-fp.y));


    }
    if(touch.phase == TouchPhase.Ended)
    {
    angle = Mathf.Atan2((lp.x-fp.x),(lp.y-fp.y))*57.2957795f;

    if(angle > 60 && angle < 120 && swipeDistanceX > 40)
    {

    //print ("right");
    swipe[0] = true;
    ApplyRightLeftForce(1);
    }


    if(angle > 150 || angle < -150 && swipeDistanceY > 40)
    {
    //print ("down");
    swipe[1] = true;
    ApplyForwBackForce(-1);
    }
    if(angle < -60 && angle > -120 && swipeDistanceX > 40)
    {
    //print ("left");
    swipe[2] = true;
    ApplyRightLeftForce(-1);
    }
    if(angle > -30 && angle < 30 && swipeDistanceY > 40)
    {
    //print ("up");
    swipe[3] = true;
    ApplyForwBackForce(1);
    }



    SetSwipe();

    }
    }

    if(Input.GetKeyDown(KeyCode.UpArrow))
    {
    ApplyForwBackForce(1);
    }
    if(Input.GetKeyDown(KeyCode.RightArrow))
    {
    ApplyRightLeftForce(1);
    }


    }


    void OnCollisionEnter(Collision collision)
    {
    if (!canJump)
    {
    canJump = true;
    }
    }



    void ApplyRightLeftForce(int dir)
    {
    Vector3 right= Camera.main.transform.TransformDirection(Vector3.right);
    right.y = 0;
    right = right.normalized;

    Vector3 rightForce = new Vector3();
    rightForce = right * dir * 0.8f * moveSpeed;
    rigidbody.AddForce(rightForce);
    }

    void ApplyForwBackForce(int dir)
    {
    Vector3 forward = Camera.main.transform.TransformDirection(Vector3.forward);
    forward.y = 0;
    forward = forward.normalized;

    Vector3 forwardForce = new Vector3();
    forwardForce = forward * dir * 1f * moveSpeed;
    rigidbody.AddForce(forwardForce);
    }

    private bool CheckSwipeDone()
    {
    bool flag = false;
    foreach(bool i in swipe)
    {
    if(i == true)
    flag = true;
    }
    return flag;
    }

    void SetSwipe()
    {
    for(int i = 0; i < swipe.Length; i++)
    swipe = false;
    }
    }

    Plz Help Me:
    I want to swipe it in 8 directions...this is for 4 directions up right left and down...I want the corners also so plz help me...
     
  28. RamilOdabaca

    RamilOdabaca

    Joined:
    Jun 28, 2013
    Posts:
    3
    i had it going, it can already detect 8 directional swipe, the problem is it doesnt make my game object move, even a little,.
    i already assigned the script to my game object,, please help, thanks in advance
     
  29. DeveshPandey

    DeveshPandey

    Joined:
    Sep 30, 2012
    Posts:
    206
  30. SenseEater

    SenseEater

    Joined:
    Nov 28, 2014
    Posts:
    19
    The Script is kind of flawed i would say in terms of Direction Detection. If you try to swipe along diagonals it will return unwanted results. Also in case your start and end touch/clicks are ending on same position , the script would still result in swipe+direction detection which in most cases is totally unwanted.

    following is a chunk that you can replace for better swipe directions as it accounts for diagonals and returns a direction from 4 Directions(Up , Down , Right , Left) based on relative drag along the two axes.

    Replace this:
    Code (CSharp):
    1.  
    2.                 // Swipe up
    3.                 if (currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
    4.                     swipeDirection = Swipe.Up;
    5.                 // Swipe down
    6.                 } else if (currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
    7.                     swipeDirection = Swipe.Down;
    8.                 // Swipe left
    9.                 } else if (currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
    10.                     swipeDirection = Swipe.Left;
    11.                 // Swipe right
    12.                 } else if (currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
    13.                     swipeDirection = Swipe.Right;
    14.                 }

    with this

    Code (CSharp):
    1.  
    2. if (!(secondPressPos == firstPressPos))
    3.      {
    4.             if (Mathf.Abs(currentSwipe.x) > Mathf.Abs(currentSwipe.y))
    5.             {
    6.                 if (currentSwipe.x < 0)
    7.                 {
    8.                     // Swipe Right          
    9.                 }
    10.                 else
    11.                 {
    12.                     //Swipe Left
    13.                 }
    14.             }
    15.             else
    16.             {
    17.                 if (currentSwipe.y < 0)
    18.                 {
    19.                     // Swipe Down
    20.                 }
    21.                 else
    22.                 {
    23.                     //Swipe Up
    24.                 }
    25.             }
    26. }
    27.  
     
  31. djfunkey

    djfunkey

    Joined:
    Jul 16, 2012
    Posts:
    201
    We could put these in static bool methods for easier use instead of adding them to ever script. ;)
    So...
    Code (CSharp):
    1. static Bool SwipeUp () {
    2.     if(currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
    3.         return true;
    4.     else return false;
    5. }
    And then just call the function from another script like such;
    Code (CSharp):
    1. if (SwipeUp()) {
    2.     //Do logic
    3. }
     
    Last edited: Nov 29, 2014
  32. Edmosis13

    Edmosis13

    Joined:
    Jan 27, 2014
    Posts:
    5
    Hi All,

    I have updated/combined Brad Keys and Gustov's code to implement a script that can detect swipes from touch and mouse (which I required for in editor testing).

    Hope it helps.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public enum Swipe { None, Up, Down, Left, Right };
    5.  
    6. public class SwipeManager : MonoBehaviour
    7. {
    8.     public float minSwipeLength = 5f;
    9.     Vector2 firstPressPos;
    10.     Vector2 secondPressPos;
    11.     Vector2 currentSwipe;
    12.  
    13.     Vector2 firstClickPos;
    14.     Vector2 secondClickPos;
    15.    
    16.     public static Swipe swipeDirection;
    17.    
    18.     void Update ()
    19.     {
    20.         DetectSwipe();
    21.     }
    22.    
    23.     public void DetectSwipe ()
    24.     {
    25.         if (Input.touches.Length > 0) {
    26.             Touch t = Input.GetTouch(0);
    27.            
    28.             if (t.phase == TouchPhase.Began) {
    29.                 firstPressPos = new Vector2(t.position.x, t.position.y);
    30.             }
    31.            
    32.             if (t.phase == TouchPhase.Ended) {
    33.                 secondPressPos = new Vector2(t.position.x, t.position.y);
    34.                 currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    35.                
    36.                 // Make sure it was a legit swipe, not a tap
    37.                 if (currentSwipe.magnitude < minSwipeLength) {
    38.                     swipeDirection = Swipe.None;
    39.                     return;
    40.                 }
    41.                
    42.                 currentSwipe.Normalize();
    43.                
    44.                 // Swipe up
    45.                 if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    46.                     swipeDirection = Swipe.Up;
    47.                     // Swipe down
    48.                 } else if (currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    49.                     swipeDirection = Swipe.Down;
    50.                     // Swipe left
    51.                 } else if (currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    52.                     swipeDirection = Swipe.Left;
    53.                     // Swipe right
    54.                 } else if (currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    55.                     swipeDirection = Swipe.Right;
    56.                 }
    57.             }
    58.         } else {
    59.  
    60.             if (Input.GetMouseButtonDown(0)) {
    61.             firstClickPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    62.             } else {
    63.                 swipeDirection = Swipe.None;
    64.                 //Debug.Log ("None");
    65.             }
    66.             if (Input.GetMouseButtonUp (0)){
    67.                 secondClickPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    68.                 currentSwipe = new Vector3(secondClickPos.x - firstClickPos.x, secondClickPos.y - firstClickPos.y);
    69.  
    70.                 // Make sure it was a legit swipe, not a tap
    71.                 if (currentSwipe.magnitude < minSwipeLength) {
    72.                     swipeDirection = Swipe.None;
    73.                     return;
    74.                 }
    75.                
    76.                 currentSwipe.Normalize();
    77.  
    78.                 //Swipe directional check
    79.                 // Swipe up
    80.                 if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    81.                     swipeDirection = Swipe.Up;
    82.                     // Swipe down
    83.                 } else if (currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {
    84.                     swipeDirection = Swipe.Down;
    85.                     // Swipe left
    86.                 } else if (currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    87.                     swipeDirection = Swipe.Left;
    88.                     Debug.Log ("Left");
    89.                     // Swipe right
    90.                 } else if (currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {
    91.                     swipeDirection = Swipe.Right;
    92.                     Debug.Log ("right");
    93.                 }
    94.             }
    95.  
    96.         }
    97.     }
    98. }
     
    jnthncr and JEulerium like this.
  33. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    You are great! I have updated this code with 8-directions and have the following:
    Code (CSharp):
    1. public enum Swipe {
    2.     None,
    3.     Up,
    4.     Down,
    5.     Left,
    6.     Right,
    7.     UpLeft,
    8.     UpRight,
    9.     DownLeft,
    10.     DownRight
    11. };
    12.  
    13. public class GestureRecognizer : MonoBehaviour {
    14.     // Min length to detect the Swipe
    15.     public float MinSwipeLength = 5f;
    16.  
    17.     private Vector2 _firstPressPos;
    18.     private Vector2 _secondPressPos;
    19.     private Vector2 _currentSwipe;
    20.  
    21.     private Vector2 _firstClickPos;
    22.     private Vector2 _secondClickPos;
    23.  
    24.     public static Swipe SwipeDirection;
    25.     public float ReturnForce = 10f;
    26.  
    27.     private void Update() {
    28.         DetectSwipe();
    29.     }
    30.  
    31.     public void DetectSwipe() {
    32.         if ( Input.touches.Length > 0 ) {
    33.             Touch t = Input.GetTouch( 0 );
    34.  
    35.             if ( t.phase == TouchPhase.Began ) {
    36.                 _firstPressPos = new Vector2( t.position.x, t.position.y );
    37.             }
    38.  
    39.             if ( t.phase == TouchPhase.Ended ) {
    40.                 _secondPressPos = new Vector2( t.position.x, t.position.y );
    41.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    42.  
    43.                 // Make sure it was a legit swipe, not a tap
    44.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    45.                     SwipeDirection = Swipe.None;
    46.                     return;
    47.                 }
    48.  
    49.                 _currentSwipe.Normalize();
    50.  
    51.                 // Swipe up
    52.                 if ( _currentSwipe.y > 0 && _currentSwipe.x > -0.5f && _currentSwipe.x < 0.5f ) {
    53.                     SwipeDirection = Swipe.Up;
    54.                 }
    55.                     // Swipe down
    56.                 else if ( _currentSwipe.y < 0 && _currentSwipe.x > -0.5f && _currentSwipe.x < 0.5f ) {
    57.                     SwipeDirection = Swipe.Down;
    58.                 }
    59.                     // Swipe left
    60.                 else if ( _currentSwipe.x < 0 && _currentSwipe.y > -0.5f && _currentSwipe.y < 0.5f ) {
    61.                     SwipeDirection = Swipe.Left;
    62.                 }
    63.                     // Swipe right
    64.                 else if ( _currentSwipe.x > 0 && _currentSwipe.y > -0.5f && _currentSwipe.y < 0.5f ) {
    65.                     SwipeDirection = Swipe.Right;
    66.                 }
    67.                     // Swipe up left
    68.                 else if ( _currentSwipe.y > 0 && _currentSwipe.x < 0 ) {
    69.                     SwipeDirection = Swipe.UpLeft;
    70.                 }
    71.                     // Swipe up right
    72.                 else if ( _currentSwipe.y > 0 && _currentSwipe.x > 0 ) {
    73.                     SwipeDirection = Swipe.UpRight;
    74.                 }
    75.                     // Swipe down left
    76.                 else if ( _currentSwipe.y < 0 && _currentSwipe.x < 0 ) {
    77.                     SwipeDirection = Swipe.DownLeft;
    78.  
    79.                     // Swipe down right
    80.                 } else if ( _currentSwipe.y < 0 && _currentSwipe.x > 0 ) {
    81.                     SwipeDirection = Swipe.DownRight;
    82.                 }
    83.             }
    84.         } else {
    85.             if ( Input.GetMouseButtonDown( 0 ) ) {
    86.                 _firstClickPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    87.             } else {
    88.                 SwipeDirection = Swipe.None;
    89.                 //Debug.Log ("None");
    90.             }
    91.             if ( Input.GetMouseButtonUp( 0 ) ) {
    92.                 _secondClickPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    93.                 _currentSwipe = new Vector3( _secondClickPos.x - _firstClickPos.x, _secondClickPos.y - _firstClickPos.y );
    94.  
    95.                 // Make sure it was a legit swipe, not a tap
    96.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    97.                     SwipeDirection = Swipe.None;
    98.                     return;
    99.                 }
    100.  
    101.                 _currentSwipe.Normalize();
    102.  
    103.                 //Swipe directional check
    104.                 // Swipe up
    105.                 if ( _currentSwipe.y > 0 && _currentSwipe.x > -0.5f && _currentSwipe.x < 0.5f ) {
    106.                     SwipeDirection = Swipe.Up;
    107.                     Debug.Log( "Up" );
    108.                 }
    109.                     // Swipe down
    110.                 else if ( _currentSwipe.y < 0 && _currentSwipe.x > -0.5f && _currentSwipe.x < 0.5f ) {
    111.                     SwipeDirection = Swipe.Down;
    112.                     Debug.Log( "Down" );
    113.                 }
    114.                     // Swipe left
    115.                 else if ( _currentSwipe.x < 0 && _currentSwipe.y > -0.5f && _currentSwipe.y < 0.5f ) {
    116.                     SwipeDirection = Swipe.Left;
    117.                     Debug.Log( "Left" );
    118.                 }
    119.                     // Swipe right
    120.                 else if ( _currentSwipe.x > 0 && _currentSwipe.y > -0.5f && _currentSwipe.y < 0.5f ) {
    121.                     SwipeDirection = Swipe.Right;
    122.                     Debug.Log( "right" );
    123.                 }     // Swipe up left
    124.                 else if ( _currentSwipe.y > 0 && _currentSwipe.x < 0 ) {
    125.                     SwipeDirection = Swipe.UpLeft;
    126.                     Debug.Log( "UpLeft" );
    127.  
    128.                 }
    129.                     // Swipe up right
    130.                 else if ( _currentSwipe.y > 0 && _currentSwipe.x > 0 ) {
    131.                     SwipeDirection = Swipe.UpRight;
    132.                     Debug.Log( "UpRight" );
    133.  
    134.                 }
    135.                     // Swipe down left
    136.                 else if ( _currentSwipe.y < 0 && _currentSwipe.x < 0 ) {
    137.                     SwipeDirection = Swipe.DownLeft;
    138.                     Debug.Log( "DownLeft" );
    139.                     // Swipe down right
    140.                 } else if ( _currentSwipe.y < 0 && _currentSwipe.x > 0 ) {
    141.                     SwipeDirection = Swipe.DownRight;
    142.                     Debug.Log( "DownRight" );
    143.                 }
    144.             }
    145.         }
    146.     }
     
    spencerz, jnthncr and Korudo like this.
  34. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    Hey all!
    I came across this thread whilst searching for touch gestures and it's exactly what I need!

    I've come to post my personal updates to see if anyone finds it useful. I've mainly switched the gesture detection to use dot products, which allows one to detect a nice 90 degree angle for each of the cardinal axes without too many comparisons, and will make it easy to upgrade to 8 directions - or more.

    Code (CSharp):
    1.     class getCardinalDirections
    2.     {
    3. // helper class, returns a direction vector to test against.
    4.         public static Vector2 up = new Vector2(0,1);
    5.         public static Vector2 down = new Vector2(0,-1);
    6.         public static Vector2 right = new Vector2(1,0);
    7.         public static Vector2 left = new Vector2(-1,0);
    8.  
    9.     }
    10.  
    11.                 if(Vector2.Dot (currentSwipe, getCardinalDirections.up)>0.5f)
    12.                 {
    13.                     swipeDirection=Swipe.Up;
    14.                     print ("UP!");
    15.                     return;
    16.                 }
    17.                 if(Vector2.Dot (currentSwipe, getCardinalDirections.down)>0.5f)
    18.                 {
    19.                     swipeDirection=Swipe.Down;
    20.                     print ("Down!");
    21.                     return;
    22.                 }
    23.                 if(Vector2.Dot (currentSwipe, getCardinalDirections.left)>0.5f)
    24.                 {
    25.                     swipeDirection=Swipe.Left;
    26.                     print ("Left");
    27.                     return;
    28.                 }
    29.                 if(Vector2.Dot (currentSwipe, getCardinalDirections.right)>0.5f)
    30.                 {
    31.                     swipeDirection=Swipe.Right;
    32.                     print ("Right");
    33.                     return;
    34.                 }
     
  35. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    Bwa, I think the code fragment I posted above is not too clear. I'm posting the full script. Note that while I do have the 8 cardinal directions, I'm not using them in the code. If you do, compare them against a dot product >0.906f (Acos(0.906f) ~ 25 degrees)


    Code (CSharp):
    1.  
    2. usingUnityEngine;
    3.  
    4.  
    5. publicclassSwipeManager : MonoBehaviour
    6. {
    7. publicfloatminSwipeCm = 0.5f;
    8. publicfloatmaxSwipeTime = 1.5f;
    9. Vector2firstPressPos;
    10. Vector2secondPressPos;
    11. Vector2currentSwipe;
    12.  
    13. publicstaticSwipeswipeDirection;
    14.  
    15.  
    16.  
    17.  
    18.  
    19. floatcurrentDPI=72;
    20. floatDPCM=24;
    21.  
    22. voidStart()
    23.  {
    24. if(Screen.dpi==0)
    25.  {
    26. currentDPI = 72;
    27.  }
    28. else
    29.  {
    30. currentDPI = Screen.dpi;
    31.  }
    32. DPCM = currentDPI/2.54f;
    33.  
    34.  }
    35.  
    36. voidUpdate ()
    37.  {
    38. DetectSwipe();
    39.  }
    40.  
    41. classgetCardinalDirections
    42.  {
    43. publicstaticVector2up = newVector2(0,1).normalized;
    44. publicstaticVector2down = newVector2(0,-1);
    45. publicstaticVector2right = newVector2(1,0);
    46. publicstaticVector2left = newVector2(-1,0);
    47.  
    48. publicstaticVector2upright = newVector2(1,1).normalized;
    49. publicstaticVector2upleft = newVector2(-1,1).normalized;
    50. publicstaticVector2downright = newVector2(1,-1).normalized;
    51. publicstaticVector2downleft = newVector2(-1,-1).normalized;
    52.  }
    53.  
    54.  
    55. publicvoidDetectSwipe ()
    56.  {
    57. if (Input.touches.Length > 0) {
    58. Toucht = Input.GetTouch(0);
    59.  
    60. if (t.phase == TouchPhase.Began) {
    61. firstPressPos = newVector2(t.position.x, t.position.y);
    62.  }
    63.  
    64. if (t.phase == TouchPhase.Ended) {
    65.  
    66. secondPressPos = newVector2(t.position.x, t.position.y);
    67. currentSwipe = newVector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
    68.  
    69.  
    70. //print ("SwipePixelDist: " + currentSwipe.magnitude + "Inches: " + currentSwipe.magnitude/currentDPI);
    71.  
    72. floatswipeCm = currentSwipe.magnitude/DPCM;
    73.  
    74.  
    75. //Makesureitwasalegitswipe, notatap
    76. if (swipeCm < minSwipeCm) {
    77. hook.ninjaCatJump ();
    78. swipeDirection = Swipe.None;
    79. return;
    80.  }
    81.  
    82.  
    83. currentSwipe.Normalize();
    84.  
    85. //usedotproductagainst4cardinaldirections.
    86. //returnifoneofthemis > 0.5f;
    87.  
    88.  
    89. //comparenorth
    90. if(Vector2.Dot (currentSwipe, getCardinalDirections.up)>0.707f)
    91.  {
    92.  
    93. swipeDirection=Swipe.Up;
    94. return;
    95.  }
    96. if(Vector2.Dot (currentSwipe, getCardinalDirections.down)>0.707f)
    97.  {
    98.  
    99.  
    100. swipeDirection=Swipe.Down;
    101. return;
    102.  }
    103. if(Vector2.Dot (currentSwipe, getCardinalDirections.left)>0.707f)
    104.  {
    105.  
    106.  
    107. swipeDirection=Swipe.Left;
    108. return;
    109.  }
    110. if(Vector2.Dot (currentSwipe, getCardinalDirections.right)>0.707f)
    111.  {
    112.  
    113.  
    114. swipeDirection=Swipe.Right;
    115. return;
    116.  }
    117.  
    118.  
    119.  }
    120.  }
    121. else {
    122. swipeDirection = Swipe.None;
    123.  }
    124.  }
    125. }
    126.  
     
    Last edited: Feb 17, 2015
    JEulerium likes this.
  36. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    I'm sorry, but how I can modify code to correctly handle 8 directions? I have use the :
    Code (CSharp):
    1. if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) > 0.25f ) {
    2.                     SwipeDirection = Swipe.UpRight;
    3.                     print( "UpRight" );
    4.                     return;
    5.                 }
    But of course, the UP is fired firstly. If I use that comparison inside the UP, UP will never fire. I am noobie, so maybe this is stupid question. :)
     
  37. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    Of course, i've adapted this for mouse. The current code is the following:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public enum Swipe { None, Up, Down, Left, Right, UpRight, UpLeft, DownRight, DownLeft  };
    5.  
    6. public class SwipeManager : MonoBehaviour {
    7.     public float MinSwipeLength = 5;
    8.     Vector2 _firstPressPos;
    9.     Vector2 _secondPressPos;
    10.     Vector2 _currentSwipe;
    11.  
    12.     public static Swipe SwipeDirection;
    13.  
    14.     void Update() {
    15.         DetectSwipe();
    16.     }
    17.  
    18.     class GetCardinalDirections {
    19.         public static readonly Vector2 Up = new Vector2( 0, 1 );
    20.         public static readonly Vector2 Down = new Vector2( 0, -1 );
    21.         public static readonly Vector2 Right = new Vector2( 1, 0 );
    22.         public static readonly Vector2 Left = new Vector2( -1, 0 );
    23.  
    24.         public static readonly Vector2 UpRight = new Vector2( 1, 1 );
    25.         public static readonly Vector2 UpLeft = new Vector2( -1, 1 );
    26.         public static readonly Vector2 DownRight = new Vector2( 1, -1 );
    27.         public static readonly Vector2 DownLeft = new Vector2( -1, -1 );
    28.     }
    29.  
    30.  
    31.     public void DetectSwipe() {
    32.         if ( Input.touches.Length > 0 ) {
    33.             Touch t = Input.GetTouch( 0 );
    34.  
    35.             if ( t.phase == TouchPhase.Began ) {
    36.                 _firstPressPos = new Vector2( t.position.x, t.position.y );
    37.             }
    38.  
    39.             if ( t.phase == TouchPhase.Ended ) {
    40.  
    41.                 _secondPressPos = new Vector2( t.position.x, t.position.y );
    42.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    43.  
    44.  
    45.                 // Make sure it was a legit swipe, not a tap
    46.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    47.                     SwipeDirection = Swipe.None;
    48.                     return;
    49.                 }
    50.  
    51.  
    52.                 _currentSwipe.Normalize();
    53.  
    54.                 // use dot product against 4 cardinal directions.
    55.                 // return if one of them is > 0.5f;
    56.  
    57.  
    58.                 //compare north
    59.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Up ) > 0.5f ) {
    60.                     SwipeDirection = Swipe.Up;
    61.                     print( "Up!" );
    62.                     return;
    63.                 }
    64.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Down ) > 0.5f ) {
    65.                     SwipeDirection = Swipe.Down;
    66.                     print( "Down!" );
    67.                     return;
    68.                 }
    69.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Left ) > 0.5f ) {
    70.                     SwipeDirection = Swipe.Left;
    71.                     print( "Left" );
    72.                     return;
    73.                 }
    74.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Right ) > 0.5f ) {
    75.                     SwipeDirection = Swipe.Right;
    76.                     print( "Right" );
    77.                     return;
    78.                 }
    79.  
    80.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) > 0.25f ) {
    81.                     SwipeDirection = Swipe.UpRight;
    82.                     print( "UpRight" );
    83.                     return;
    84.                 }
    85.  
    86.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpLeft ) > 0.25f ) {
    87.                     SwipeDirection = Swipe.UpLeft;
    88.                     print( "UpLeft" );
    89.                     return;
    90.                 }
    91.  
    92.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownLeft ) > 0.25f ) {
    93.                     SwipeDirection = Swipe.DownLeft;
    94.                     print( "DownLeft" );
    95.                     return;
    96.                 }
    97.  
    98.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownRight ) > 0.25f ) {
    99.                     SwipeDirection = Swipe.DownRight;
    100.                     print( "DownRight" );
    101.                     return;
    102.                 }
    103.             }
    104.         } else {
    105.             if ( Input.GetMouseButtonDown( 0 ) ) {
    106.                 _firstPressPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    107.             } else {
    108.                 SwipeDirection = Swipe.None;
    109.                 //Debug.Log ("None");
    110.             }
    111.             if ( Input.GetMouseButtonUp( 0 ) ) {
    112.                 _secondPressPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    113.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    114.  
    115.                 // Make sure it was a legit swipe, not a tap
    116.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    117.                     SwipeDirection = Swipe.None;
    118.                     return;
    119.                 }
    120.  
    121.                 _currentSwipe.Normalize();
    122.  
    123.                 //Swipe directional check and it is not working at the moment.
    124.                 // Swipe up
    125.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Up ) > 0.5f ) {
    126.                     if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) > 0.25f ) {
    127.                         SwipeDirection = Swipe.UpRight;
    128.                         print( "UpRight" );
    129.                         return;
    130.                     }
    131.                     if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpLeft ) > 0.25f ) {
    132.                         SwipeDirection = Swipe.UpLeft;
    133.                         print( "UpLeft" );
    134.                         return;
    135.                     }
    136.                     SwipeDirection = Swipe.Up;
    137.                     print( "Up!" );
    138.                     return;
    139.                 }
    140.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Down ) > 0.5f ) {
    141.                     if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownLeft ) > 0.25f ) {
    142.                         SwipeDirection = Swipe.DownLeft;
    143.                         print( "DownLeft" );
    144.                         return;
    145.                     }
    146.                     if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownRight ) > 0.25f ) {
    147.                         SwipeDirection = Swipe.DownRight;
    148.                         print( "DownRight" );
    149.                         return;
    150.                     }
    151.                     SwipeDirection = Swipe.Down;
    152.                     print( "Down!" );
    153.                     return;
    154.                 }
    155.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Left ) > 0.5f ) {
    156.                     SwipeDirection = Swipe.Left;
    157.                     print( "Left" );
    158.                     return;
    159.                 }
    160.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Right ) > 0.5f ) {
    161.                     SwipeDirection = Swipe.Right;
    162.                     print( "Right" );
    163.                     return;
    164.                 }
    165.             }
    166.         }
    167.     }
    168. }
    169.  
     
    jnthncr likes this.
  38. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    Hey JEulerium, I think you will need to compare the up/down/left/right dot products against 0.25 as well for the code to work! Also, not sure why you have nested if statements in your mouse logic.
     
  39. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    Hi! I put the 0.25 everywhere, but it still detects only UP (if i drag upper left or right)

    Code (CSharp):
    1. public class SwipeManager : MonoBehaviour {
    2.     public float MinSwipeLength = 5;
    3.     Vector2 _firstPressPos;
    4.     Vector2 _secondPressPos;
    5.     Vector2 _currentSwipe;
    6.  
    7.     public static Swipe SwipeDirection;
    8.  
    9.     void Update() {
    10.         DetectSwipe();
    11.     }
    12.  
    13.     class GetCardinalDirections {
    14.         public static readonly Vector2 Up = new Vector2( 0, 1 );
    15.         public static readonly Vector2 Down = new Vector2( 0, -1 );
    16.         public static readonly Vector2 Right = new Vector2( 1, 0 );
    17.         public static readonly Vector2 Left = new Vector2( -1, 0 );
    18.  
    19.         public static readonly Vector2 UpRight = new Vector2( 1, 1 );
    20.         public static readonly Vector2 UpLeft = new Vector2( -1, 1 );
    21.         public static readonly Vector2 DownRight = new Vector2( 1, -1 );
    22.         public static readonly Vector2 DownLeft = new Vector2( -1, -1 );
    23.     }
    24.  
    25.  
    26.     public void DetectSwipe() {
    27.         if ( Input.touches.Length > 0 ) {
    28.             Touch t = Input.GetTouch( 0 );
    29.  
    30.             if ( t.phase == TouchPhase.Began ) {
    31.                 _firstPressPos = new Vector2( t.position.x, t.position.y );
    32.             }
    33.  
    34.             if ( t.phase == TouchPhase.Ended ) {
    35.  
    36.                 _secondPressPos = new Vector2( t.position.x, t.position.y );
    37.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    38.  
    39.  
    40.                 // Make sure it was a legit swipe, not a tap
    41.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    42.                     SwipeDirection = Swipe.None;
    43.                     return;
    44.                 }
    45.  
    46.  
    47.                 _currentSwipe.Normalize();
    48.  
    49.                 // use dot product against 4 cardinal directions.
    50.                 // return if one of them is > 0.5f;
    51.  
    52.  
    53.                 //compare north
    54.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Up ) > 0.25f ) {
    55.                     SwipeDirection = Swipe.Up;
    56.                     print( "Up!" );
    57.                     return;
    58.                 }
    59.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Down ) > 0.25f ) {
    60.                     SwipeDirection = Swipe.Down;
    61.                     print( "Down!" );
    62.                     return;
    63.                 }
    64.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Left ) > 0.25f ) {
    65.                     SwipeDirection = Swipe.Left;
    66.                     print( "Left" );
    67.                     return;
    68.                 }
    69.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Right ) > 0.25f ) {
    70.                     SwipeDirection = Swipe.Right;
    71.                     print( "Right" );
    72.                     return;
    73.                 }
    74.  
    75.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) > 0.25f ) {
    76.                     SwipeDirection = Swipe.UpRight;
    77.                     print( "UpRight" );
    78.                     return;
    79.                 }
    80.  
    81.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpLeft ) > 0.25f ) {
    82.                     SwipeDirection = Swipe.UpLeft;
    83.                     print( "UpLeft" );
    84.                     return;
    85.                 }
    86.  
    87.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownLeft ) > 0.25f ) {
    88.                     SwipeDirection = Swipe.DownLeft;
    89.                     print( "DownLeft" );
    90.                     return;
    91.                 }
    92.  
    93.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownRight ) > 0.25f ) {
    94.                     SwipeDirection = Swipe.DownRight;
    95.                     print( "DownRight" );
    96.                     return;
    97.                 }
    98.             }
    99.         } else {
    100.             if ( Input.GetMouseButtonDown( 0 ) ) {
    101.                 _firstPressPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    102.             } else {
    103.                 SwipeDirection = Swipe.None;
    104.                 //Debug.Log ("None");
    105.             }
    106.             if ( Input.GetMouseButtonUp( 0 ) ) {
    107.                 _secondPressPos = new Vector2( Input.mousePosition.x, Input.mousePosition.y );
    108.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    109.  
    110.                 // Make sure it was a legit swipe, not a tap
    111.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    112.                     SwipeDirection = Swipe.None;
    113.                     return;
    114.                 }
    115.  
    116.                 _currentSwipe.Normalize();
    117.  
    118.                 //Swipe directional check
    119.                 // Swipe up
    120.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Up ) > 0.25f ) {
    121.                     SwipeDirection = Swipe.Up;
    122.                     print( "Up!" );
    123.                     return;
    124.                 }
    125.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Down ) > 0.25f ) {
    126.                     SwipeDirection = Swipe.Down;
    127.                     print( "Down!" );
    128.                     return;
    129.                 }
    130.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Left ) > 0.25f ) {
    131.                     SwipeDirection = Swipe.Left;
    132.                     print( "Left" );
    133.                     return;
    134.                 }
    135.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Right ) > 0.25f ) {
    136.                     SwipeDirection = Swipe.Right;
    137.                     print( "Right" );
    138.                     return;
    139.                 }
    140.  
    141.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) > 0.25f ) {
    142.                     SwipeDirection = Swipe.UpRight;
    143.                     print( "UpRight" );
    144.                     return;
    145.                 }
    146.  
    147.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpLeft ) > 0.25f ) {
    148.                     SwipeDirection = Swipe.UpLeft;
    149.                     print( "UpLeft" );
    150.                     return;
    151.                 }
    152.  
    153.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownLeft ) > 0.25f ) {
    154.                     SwipeDirection = Swipe.DownLeft;
    155.                     print( "DownLeft" );
    156.                     return;
    157.                 }
    158.  
    159.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownRight ) > 0.25f ) {
    160.                     SwipeDirection = Swipe.DownRight;
    161.                     print( "DownRight" );
    162.                     return;
    163.                 }
    164.             }
    165.         }
    166.     }
    167. }
     
  40. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    Durrr, I am sooo stupid. Try again, comparing against 0.906f - ACos(0.906) ~ 25 degrees.

    EDIT: I also updated my code fragment so that it uses dpi, so we can use physical length to detect touches. And I have no idea why my code fragment comes in unformatted >.>
     
    Last edited: Feb 17, 2015
  41. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    I need to put 0.906f - AXos(0.906) everywhere in comparison? I put, and still not working...
     
  42. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    Just replace 0.5f with 0.906f, that should do the trick.
     
  43. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
    This is what I tested with last night, defo works.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Swipe2Test : MonoBehaviour {
    5.     public float MinSwipeLength = 5;
    6.     Vector2 _firstPressPos;
    7.     Vector2 _secondPressPos;
    8.     Vector2 _currentSwipe;
    9.    
    10.     public static Swipe SwipeDirection;
    11.    
    12.     void Update() {
    13.         DetectSwipe();
    14.     }
    15.    
    16.     class GetCardinalDirections {
    17.         public static readonly Vector2 Up = new Vector2( 0, 1 );
    18.         public static readonly Vector2 Down = new Vector2( 0, -1 );
    19.         public static readonly Vector2 Right = new Vector2( 1, 0 );
    20.         public static readonly Vector2 Left = new Vector2( -1, 0 );
    21.        
    22.         public static readonly Vector2 UpRight = new Vector2( 1, 1 );
    23.         public static readonly Vector2 UpLeft = new Vector2( -1, 1 );
    24.         public static readonly Vector2 DownRight = new Vector2( 1, -1 );
    25.         public static readonly Vector2 DownLeft = new Vector2( -1, -1 );
    26.     }
    27.    
    28.    
    29.     public void DetectSwipe() {
    30.         if ( Input.touches.Length > 0 ) {
    31.             Touch t = Input.GetTouch( 0 );
    32.            
    33.             if ( t.phase == TouchPhase.Began ) {
    34.                 _firstPressPos = new Vector2( t.position.x, t.position.y );
    35.             }
    36.            
    37.             if ( t.phase == TouchPhase.Ended ) {
    38.                
    39.                 _secondPressPos = new Vector2( t.position.x, t.position.y );
    40.                 _currentSwipe = new Vector3( _secondPressPos.x - _firstPressPos.x, _secondPressPos.y - _firstPressPos.y );
    41.                
    42.                
    43.                 // Make sure it was a legit swipe, not a tap
    44.                 if ( _currentSwipe.magnitude < MinSwipeLength ) {
    45.                     SwipeDirection = Swipe.None;
    46.                     return;
    47.                 }
    48.                
    49.                
    50.                 _currentSwipe.Normalize();
    51.                
    52.                 // use dot product against 4 cardinal directions.
    53.                 // return if one of them is > 0.5f;
    54.  
    55.                 print (_currentSwipe);
    56.                
    57.                 //compare north
    58.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Up ) > 0.906f ) {
    59.  
    60.                     print( "Up!" );
    61.                     return;
    62.                 }
    63.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Down ) > 0.906f ) {
    64.                     print( "Down!" );
    65.                     return;
    66.                 }
    67.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Left ) > 0.906f ) {
    68.                     print( "Left" );
    69.                     return;
    70.                 }
    71.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.Right ) > 0.906f) {
    72.                     print( "Right" );
    73.                     return;
    74.                 }
    75.                
    76.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpRight ) >0.906f ) {
    77.                     print( "UpRight" );
    78.                     return;
    79.                 }
    80.                
    81.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.UpLeft ) > 0.906f ) {
    82.                     print( "UpLeft" );
    83.                     return;
    84.                 }
    85.                
    86.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownLeft ) > 0.906f ) {
    87.                     print( "DownLeft" );
    88.                     return;
    89.                 }
    90.                
    91.                 if ( Vector2.Dot( _currentSwipe, GetCardinalDirections.DownRight ) > 0.906f) {
    92.                     print( "DownRight" );
    93.                     return;
    94.                 }
    95.             }
    96.        
    97.         }
    98.     }
    99. }
    100.  
     
    jnthncr, jc-drile77 and Daniel-F like this.
  44. JEulerium

    JEulerium

    Joined:
    Feb 18, 2014
    Posts:
    35
    Yeah, it is working. Thank you!
     
  45. gallenwolf

    gallenwolf

    Joined:
    Mar 11, 2012
    Posts:
    118
  46. barry1978

    barry1978

    Joined:
    Feb 16, 2013
    Posts:
    10
    for those interested, i have made a Unityscript version of this (4 directions):


    #pragmastrict

    var minSwipeLength : float = 5.0;
    private var firstPressPos : Vector2;
    private var secondPressPos : Vector2;
    private var currentSwipe : Vector2;

    private var firstClickPos : Vector2;
    private var secondClickPos : Vector2;

    function Update () {

    DetectSwipe();
    }

    function DetectSwipe () {

    if (Input.touches.Length > 0) {

    var t : Touch = Input.GetTouch(0);

    if (t.phase == TouchPhase.Began) {

    firstPressPos = newVector2(t.position.x, t.position.y);
    }

    if (t.phase == TouchPhase.Ended) {

    secondPressPos = newVector2(t.position.x, t.position.y);
    currentSwipe = newVector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);

    //Make sure it was a legit swipe, not a tap
    if (currentSwipe.magnitude < minSwipeLength) {

    //this was a tap, not a swipe
    return;
    }

    currentSwipe.Normalize();

    //Swipeup
    if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {

    //dosomething
    }
    //Swipedown
    elseif (currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {

    //dosomething
    }
    //Swipeleft
    elseif (currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {

    //dosomething
    }
    //Swiperight
    elseif (currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {

    //dosomething
    }
    }
    } else {

    if (Input.GetMouseButtonDown(0)) {

    firstClickPos = newVector2(Input.mousePosition.x, Input.mousePosition.y);
    }

    if (Input.GetMouseButtonUp (0)){

    secondClickPos = newVector2(Input.mousePosition.x, Input.mousePosition.y);
    currentSwipe = newVector3(secondClickPos.x - firstClickPos.x, secondClickPos.y - firstClickPos.y);

    //Make sure it was a legit swipe, not a click
    if (currentSwipe.magnitude < minSwipeLength) {

    //this was a click, not a swipe
    return;
    }

    currentSwipe.Normalize();

    //Swipeup
    if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {

    //dosomething
    }
    //Swipedown
    elseif (currentSwipe.y < 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f) {

    //dosomething
    }
    //Swipeleft
    elseif (currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {

    //dosomething
    }
    //Swiperight
    elseif (currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f) {

    //dosomething
    }
    }

    }
    }


    Enjoy :)

    ps: feel free to improve
     
  47. hrantn

    hrantn

    Joined:
    Jul 14, 2015
    Posts:
    1
    Thanks for code ) But i am getting a compile error like this ) help me plis
     

    Attached Files:

  48. Alec-Slayden

    Alec-Slayden

    Joined:
    Dec 16, 2008
    Posts:
    94
    I am not using that line in my code so I assume you are asking an earlier poster :)
    However I think whats happening is that boolean operators didn't translate over for some reason. Between those comparisons should be either "&&" or "||"

    it looks like "&&" is probably accurate.
     
    jimlee58 likes this.
  49. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,654
    Worth noting that there's a fantastic tool in the AssetStore called "Gesture Recognizer" which does all of this- maybe even spawned from this discussion originally. It additionally allows you to define custom (single-stroke) gesture shapes that trigger events when the user draws them on the screen. Just felt worth mentioning, as I use it rather heavily.
     
    Alec-Slayden likes this.
  50. mike6679

    mike6679

    Joined:
    Jul 31, 2015
    Posts:
    8
    Thanks!