UNITY3D: SWIPE INPUT FOR TOUCH SCREEN MOBILE DEVICE

Whenever you are developing a game for a Touch Screen device, one of the most important controls you would use is the Swipe of the screen. In this Unity Byte, we will learn how to detect this swipe on the screen.

NOTE: You might want to install Unity Remote on your Android device to test this Byte on the go.

To get started, create a New Project, save it as whatever you like. You will have a New Scene by default, you can save it by pressing ctrl+S and name it as, say SwipeInput.

Add a new C# Script by Right Clicking on the Assets folder and Create->C# Script and name it as SwipeControl. Attach it to the Main Camera.

First of all we will open the script and add some variables:

private Vector3 fp;   //First touch position
private Vector3 lp;   //Last touch position
private float dragDistance;  //minimum distance for a swipe to be registered
private List<Vector3> touchPositions = new List<Vector3>(); //store all the touch positions in list

Once the variables are added, we will set the minimum distance that the user is supposed to swipe if it is to be detected in the Start function as below

void Start(){
    dragDistance = Screen.height*20/100; //dragDistance is 20% height of the screen 
}
In the Update function we will add the logic to detect the swipe and it's direction as follows:

void Update(){

    foreach (Touch touch in Input.touches)  //use loop to detect more than one swipe
    { //can be ommitted if you are using lists 
    /*if (touch.phase == TouchPhase.Began) //check for the first touch
    {
        fp = touch.position;
        lp = touch.position;

    }*/

    if (touch.phase == TouchPhase.Moved) //add the touches to list as the swipe is being made
    {
    touchPositions.Add(touch.position);
    }

    if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
    {
        //lp = touch.position;  //last touch position. Ommitted if you use list
        fp =  touchPositions[0]; //get first touch position from the list of touches
        lp =  touchPositions[touchPositions.Count-1]; //last touch position 

        //Check if drag distance is greater than 20% of the screen height
        if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
        {//It's a drag
              //check if the drag is vertical or horizontal 
              if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
              {   //If the horizontal movement is greater than the vertical movement...
                  if ((lp.x>fp.x))  //If the movement was to the right)
                  {   //Right swipe
                      Debug.Log("Right Swipe");
                  }
                  else
                  {   //Left swipe
                      Debug.Log("Left Swipe"); 
                  }
              }
            else
            {   //the vertical movement is greater than the horizontal movement
                 if (lp.y>fp.y)  //If the movement was up
                 {   //Up swipe
                     Debug.Log("Up Swipe"); 
                 }
                 else
                 {   //Down swipe
                     Debug.Log("Down Swipe");
                 }
            }
        } 
    }
    else
    {   //It's a tap as the drag distance is less than 20% of the screen height

    }
   }
}

Note that you got to use the System.Collections.Generic namespace

I believe the comments in the above code are as descriptive as they can be, and I hope that I won't have to explain it again. (Comment below for any questions)

Once you have added this code to your script, save it and switch back to Unity. Now connect your Android device to your PC. Once the device is connected, start the Unity Remote app in your Mobile device and run the game in the editor. Now try swiping in different directions and check out for the respective logs in the console.

Download the Unity Package of this post here
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

16 comments:

  1. the fourth variable comes up with an error for me
    "A new expression requires () or [] after type"

    ReplyDelete
    Replies
    1. () were missing at the end.. Thanks for bringing it to our notice... Check it out now, I've updated the code...

      Delete
  2. Download the Unity Package of this post here "Does not work"

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. i keep getting this error after a couple swipes

    ArgumentOutOfRangeException: Argument is out of range.
    Parameter name: index

    (SwipeControl.cs:34)

    ReplyDelete
  5. I get this error message:

    Assets/SwipeControl.cs(9,17): error CS0246: The type or namespace name `List`1' could not be found. Are you missing a using directive or an assembly reference?

    Any help?

    ReplyDelete
    Replies
    1. use System.Collections.Generic namespace

      Delete
  6. Hi, the file can't be downloaded from ur dropbox. there is error. pls check

    ReplyDelete
  7. No more file at dropBox .. please send me ..
    e.teguh36@gmail.com

    ReplyDelete
  8. Help me

    SwipeControl.cs(9,13): error CS0246: The type or namespace name `List`1' could not be found. Are you missing a using directive or an assembly reference?

    ReplyDelete
    Replies
    1. using System.Collections.Generic;

      It's Work!

      Delete
  9. Do you have any codes for swipe like in temple run? (rotating the player itself)

    ReplyDelete
  10. Do you have any codes for swipe like in temple run? (rotating the player itself)

    ReplyDelete
  11. This arises from the fact that the information and data accessed and contained in them includes personal and private data, photos and contacts, and even data and security details belonging to financial accounts and other online businesses.this site

    ReplyDelete
  12. Most cell phones available today have a touchscreen. http://www.faytech.us/

    ReplyDelete