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.
    Blogger
    Facebook

27 comments:

  1. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

      Delete
  2. 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
  3. Download the Unity Package of this post here "Does not work"

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

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

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

    (SwipeControl.cs:34)

    ReplyDelete
  6. 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
  7. Hi, the file can't be downloaded from ur dropbox. there is error. pls check

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

    ReplyDelete
  9. 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
  10. Do you have any codes for swipe like in temple run? (rotating the player itself)

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

    ReplyDelete
  12. 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
  13. Most cell phones available today have a touchscreen. http://www.faytech.us/

    ReplyDelete
  14. This one is a material science orientated game, where the player needs to utilize a great deal of good judgment to finish different sorts of undertakings find this

    ReplyDelete
  15. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also large touch screen monitor

    ReplyDelete
  16. The writer has made this blog in the most stunning way. Mind boggling!
    Rogue buddies 2 unblocked

    ReplyDelete
  17. Nice to read your article! I am looking forward to sharing your adventures and experiences. The Sims Mobile Cheats

    ReplyDelete
  18. Thanks to the latest improvements in the graphical interfaces mobile phones have been using recently, high quality mobile games can be produced at little cost and served for end users at reasonable prices http://mobilegamer365.com/

    ReplyDelete
  19. Hey, i have a game on my website that uses that same technology and you can view it here..Tank Off Game

    ReplyDelete
  20. First off, think about your existing customer base and how they currently interact with your business through your website, RSS feeds, Facebook pages, and LinkedIn profile. ShowBox APK 2018

    ReplyDelete
  21. I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article... unlockmobiledevice

    ReplyDelete