Swipe in all directions Touch and Mouse

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:

//inside class
Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;

public void Swipe()
{
     if(Input.touches.Length > 0)
     {
	     Touch t = Input.GetTouch(0);
	     if(t.phase == TouchPhase.Began)
	     {
	          //save began touch 2d point
		     firstPressPos = new Vector2(t.position.x,t.position.y);
	     }
	     if(t.phase == TouchPhase.Ended)
	     {
              //save ended touch 2d point
		     secondPressPos = new Vector2(t.position.x,t.position.y);
		     				
              //create vector from the two points
		     currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
				
		     //normalize the 2d vector
		     currentSwipe.Normalize();

		     //swipe upwards
		     if(currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
		     {
			     Debug.Log("up swipe");
		     }
		     //swipe down
		     if(currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
		     {
			     Debug.Log("down swipe");
		     }
		     //swipe left
		     if(currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
		     {
			     Debug.Log("left swipe");
		     }
		     //swipe right
		     if(currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
		     {
			     Debug.Log("right swipe");
		     }
	     }
     }
}

For Mouse left click (0):

//inside class
Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;

public void Swipe()
{
     if(Input.GetMouseButtonDown(0))
     {
	     //save began touch 2d point
	  	firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
     }
	 if(Input.GetMouseButtonUp(0))
	 {
            //save ended touch 2d point
		secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
		
            //create vector from the two points
		currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);	
			
		//normalize the 2d vector
		currentSwipe.Normalize();

		//swipe upwards
		if(currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
		{
			Debug.Log("up swipe");
		}
		//swipe down
		if(currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f)
		{
			Debug.Log("down swipe");
		}
		//swipe left
		if(currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
		{
			Debug.Log("left swipe");
		}
		//swipe right
		if(currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f)
		{
			Debug.Log("right swipe");
		}
	}
}

Cheers!

16 Likes

Thank you very much for sharing this.
Works perfectly.

thank you so much, works like charm :slight_smile:

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.

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

it worked THANKS

Quick Question, does this code only do up, down, left and right or is it literally all directions? Thanks!

It only does Up, Down, Left, Right. You could easily modify it to do diagonals though and get 8 directions instead of just 4.

Here’s a new version that helps prevent taps from counting as swipes. It’s also meant to be used externally, such as…

if (SwipeManager.swipeDirection == Swipe.Up) {
    // do something...
}

And here is the new script.

using UnityEngine;

public enum Swipe { None, Up, Down, Left, Right };

public class SwipeManager : MonoBehaviour
{
    public float minSwipeLength = 200f;
    Vector2 firstPressPos;
    Vector2 secondPressPos;
    Vector2 currentSwipe;

    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) {
                    swipeDirection = Swipe.None;
                    return;
                }
            
                currentSwipe.Normalize();

                // Swipe up
                if (currentSwipe.y > 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
                    swipeDirection = Swipe.Up;
                // Swipe down
                } else if (currentSwipe.y < 0  currentSwipe.x > -0.5f  currentSwipe.x < 0.5f) {
                    swipeDirection = Swipe.Down;
                // Swipe left
                } else if (currentSwipe.x < 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
                    swipeDirection = Swipe.Left;
                // Swipe right
                } else if (currentSwipe.x > 0  currentSwipe.y > -0.5f  currentSwipe.y < 0.5f) {
                    swipeDirection = Swipe.Right;
                }
             }
        } else {
            swipeDirection = Swipe.None;
        }
    }
}

EDIT August 9, 2016:
New version here
http://forum.unity3d.com/threads/swipe-in-all-directions-touch-and-mouse.165416/page-2#post-2741253

1 Like

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.

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
}
}
}

1 Like

When I use the above three lines in another script. It always detects Swipe Up. How to solve this?

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

Try changing SwipeManager line 5 to be…

public enum Swipe { None, Up, Down, Left, Right };

It is defaulting to Swipe.Up, but this should make it default to Swipe.None.

Now, it is not recognising any swipe at all.

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.

Why not use touch.delta position, that way you can iterate through multiple touches.

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.

it works perfectly, thanks so much <3

Then just use input.getTouch[0]