Skip to main content

Simple Up, Down, Left, Right Swipe controls for touch devices( Iphone and Android) in unity

Note: There are more than 50 comments in this post, So, if your comment is not appearing on the first page than' 'don't get panic', there is a Load More button at the bottom of the page.



Here is a UnityScript (javascript version)

#pragma strict
var player : Transform;  // Drag your player here
private var fp : Vector2;  // first finger position
private var lp : Vector2;  // last finger position

function Update()
{
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fp = touch.position;
lp = touch.position;
}
if (touch.phase == TouchPhase.Moved )
{
lp = touch.position;
}
if(touch.phase == TouchPhase.Ended)
{

if((fp.x - lp.x) > 80) // left swipe
{

player.Rotate(0,-90,0);

}
else if((fp.x - lp.x) < -80) // right swipe
{
player.Rotate(0,90,0);
}
else if((fp.y - lp.y) < -80 ) // up swipe
{
// add your jumping code here
}
}
}


}


add this script to any empty gameObject or your player than drag your player to player variable in editor now build a .apk or .ipa and check the results.

Thanks to unity community for providing so many info on the swipe controls, but this one, i like the most.
comment if you have any questions related to this script just mail me at sushanta1991@rediffmail.com.

Here is a joystick solution for your touch devices, take a look
http://bit.ly/1mUhAnl

Here is another way to do swipe using angle calculation, give it a try
http://bit.ly/1mUgxUx





And a Generic solution to swipe
http://bit.ly/2nNbecC





Edit:

  

I got few request's for subway surfer like controls using swipe, so i made a sample unity project file, which does not have exact same controls like subway but almost similar, i used the above swipe script to control that character movement, hope this helps you guys to understand the swipe logic.
made with unity5.3.2 ,
http://bit.ly/29RyGO4






If you like this post and want to contribute Please click on the link given below.

https://www.paypal.me/Sushanta1991



Comments

  1. Thanks a lot for this!

    ReplyDelete
    Replies
    1. Hello!Please answer the question-how to swipe down?!

      Delete
    2. hello sushanta , how can i prevent the character from switching off lane ? he can lerp also from the side of the terrain which is off lane .. thanks , please reply

      Delete
  2. Can someone please convert it in c sharp. i am new to unity.

    ReplyDelete
    Replies
    1. Hi Asad, Here is the Cs version of the above script.

      using UnityEngine;
      using System.Collections;

      public class SwipeSimpleCS : MonoBehaviour {

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

      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;
      }
      if(touch.phase == TouchPhase.Ended)
      {
      if((fp.x - lp.x) > 80) // left swipe
      {
      player.Rotate(0,-90,0);
      }
      else if((fp.x - lp.x) < -80) // right swipe
      {
      player.Rotate(0,90,0);
      }
      else if((fp.y - lp.y) < -80 ) // up swipe
      {
      // add your jumping code here
      }
      }
      }
      }
      }

      Delete
    2. Thank you for the conversion your work is great and a great help to me.

      Delete
    3. hello where is this pasted on the player object yes?

      Delete
    4. There are 3 possibilities here that you can try, since i dont know which one you will prefer so i am showing all the possible ways.

      Actually you don't need touch here you can just use Input.acceleration.x instead of Input.GetAxis("Horizontal")

      Or if you want to use touch.deltaPosition.x, you should do it like this

      using UnityEngine;
      using System.Collections;

      public class MoveLeftAndRight : MonoBehaviour {

      public float speed = 1.0f;

      void Update () {
      foreach(Touch touch in Input.touches)
      {
      Vector3 newPosition = transform.position;
      newPosition.x += touch.deltaPosition.x * speed * Time.deltaTime;
      transform.position = newPosition;
      }
      }
      }

      Or you can use a simple logic like subway surfers,

      using UnityEngine;
      using System.Collections;

      public class MoveLeftAndRight : MonoBehaviour {

      private Vector2 fp; // first finger position
      private Vector2 lp; // last finger position

      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;
      }
      if(touch.phase == TouchPhase.Ended)
      {
      Vector3 newPosition = transform.position;
      if((fp.x - lp.x) > 80) // left swipe
      {
      newPosition.x -= speed;
      transform.position = newPosition;
      }
      else if((fp.x - lp.x) < -80) // right swipe
      {
      newPosition.x += speed;
      transform.position = newPosition;
      }
      }
      }
      }
      }

      hope this helps you..

      Delete
    5. THANK YOU SO MUCH IT WORKED I TRIED THE 2ND METHOD IVE BEEN TRYING FOR 6 MONTHS THANK YOU SO MUCH !!!!!!!!!!!!!!!!!!!!!

      Delete
    6. Hi Usman, glad to know that solution worked for you. Next time don't wait for 6 months just ask in unity forums, people's are very helpful there.

      Delete
    7. omg, I can't thank you enough! I've been searching for a while now, either complex or nothing, until i found this! Thanks :D

      Delete
    8. glad to know that, keep visiting Bassel, you are always welcome..

      Delete
  3. What does the 80 in the if statement mean?

    ReplyDelete
  4. 80 is the swipe length.
    By that i mean, what length you want user to drag his/her finger to detect a swipe gesture.

    ReplyDelete
    Replies
    1. so the biggger the number the longer the swipping? O.o Btw thanks for the source code! :)

      Delete
    2. you are most welcome Riri, and answer to your question is yes, the bigger the number the longer the swiping.

      Delete
  5. Very nice blog page...another new Unity user but a long time character game animator! I was wondering if this type of swipe gesture code could be used to trigger animation clips in unity? If so could you point me in the right direction or tell me were to embed the code in your script... thanks in advance

    ReplyDelete
    Replies
    1. glad you like the blog, and sure i would love to help you with this.

      since you want to call animation on completing a gesture, its very simple. just add these lines to the code above. "handsUpLeft" is the animation name you want to play, you can write any animation name that your character have.

      if((fp.x - lp.x) > 80) // left swipe
      {
      //player.Rotate(0,-90,0);
      animation.Play("handsUpLeft"); // this is the animation you want to play on your character
      }
      else if((fp.x - lp.x) < -80) // right swipe
      {
      //player.Rotate(0,90,0);
      animation.Play("handsUpRight"); // this is the animation you want to play on your character
      }

      put this script on your character.

      Delete
    2. Bro, your a very helpful person. Thank you! I'll give this a go today. By the way are you a freelance programmer and what is your day rate? if you are can ping me back and i'll drop you my email....If you're not available all the best :) here's a little bit of my work. https://www.youtube.com/channel/UC2YNJDLQrnUwjqZedny_sKA?feature=mhee

      Thanks, Veno

      Delete
    3. hi, I think we should do a collaboration project, a Stranger helping a Stranger no money involved, later we will see. mail me at sushanta1991@rediffmail.com
      and thanks for showing your work they are really awesome!

      Delete
    4. You truly are a awesome guy :) you can remove your email address from here i've saved it and already sent you a email. thanks

      Delete
  6. This works with my 1st o 3rd person controlar player?

    ReplyDelete
    Replies
    1. you are asking a question here ? if yes than, ya it will work with 1st or 3rd person controller. But maybe you need to customize few things as per your needs.

      Delete
  7. hi great simple coding but its saying this...

    BCE0077: It is not possible to invoke an expression of type 'boolean'.

    which is the if statements??? can you please help! this is crucial for me ;)

    ReplyDelete
    Replies
    1. Hi Jamie, I copy/paste both the script showed here to my unity and check if its showing any error or not, but everything is fine with the code above.
      could you please post your code so i can tell where is the issue ?

      Delete
    2. oh i found out why it wasnt working.. but for some reason you cant call a function in those sections where it says to add code... i had a function called jump(); but if i took out the function and just placed the code in there instead from the function then it works???
      dunno why

      Delete
    3. It should work with using functions, since its not working for you could you post your script so I could point out the issue.

      Delete
  8. hi sushanta. you are doing a great job here. i need help about swipe controls. i have a platform runner project like Temple Run or Subway Surfers but my character is not running. it's flying on x axes and it doesn't use gravity. It has 9 tracks on it's way(3x3). I want my character to move up, down, right or left when i swipe. I dont want it to rotate. It should switch between tracks. i hope you can help.

    ReplyDelete
    Replies
    1. Hi, and thanks for your nice words. if you dont want to rotate its fine instead of rotation you can just add value to players transform. like on left swipe just subtract a value from player transfrom.position.x.
      eg,
      if(leftswipe){
      transform.position.x-=5;
      }
      same for up,down and right swipe, but with respective axises.
      you can do same thing with a different way to smoothen the movement of your player while shifting lane line subway surfer and temple run.
      Hope this help you someway, ask me if you have any further queries.

      Delete
    2. i just deleted player.Rotation and paste transform.Position instead of it. but i cant play the scene because of script error. then i deleted all the script and just wrote transform.Position.x-=1 and attached it a game object. but my object doesnt stop. it moves on x axis continuously. it should. how can i stop it after it completed its move to other track

      Delete
    3. finally i've done it. thanks man.

      Delete
    4. Hey i was wondering if you can help me with something , i tried adding your script to my rubic cube game , so when i swipe down on one of the edges do a function . how can i do it so the swipe only works when it comes in contact with a gameObject ? thank you for the help!

      Delete
    5. Hi Mackensie, You can do this by casting a ray on TouchPhase.Began and if that ray hit some object than do what ever you want when TouchPhase.Ended

      Delete
    6. Hi Mackensie, this unity package contains what i mentioned above, http://bit.ly/MHBRvV

      Delete
  9. Hi Sushanth... nice blog, and nice tutorial, im not at all good with scripting. I have a game where a character needs to move (which is already coded by you) and then look left and right.

    He should also be able to use left mouse to activate triggers.

    Can you help me out!!! Thanks

    ReplyDelete
    Replies
    1. Hi Mikey, good to know you like my blogs. And ya, i would love to help. But i need to know a little more about what you want to do.

      Delete
  10. hey, i just looked at your code and it was very usefull but i just need to move the player up and down so i just changed the code a bit. but the problem is i have 2 players on 1 screen and i want to drag them seperatedly so it's a 2 player game. the issue im having with the code is when i move player 1 it also moves player 2. i hope you can help me?

    ReplyDelete
    Replies
    1. Hi Aoron, you can do one simple thing,
      Divide the screen into halfs, for player 1 use if(fp.x < Screen.width/2){ than use your logic for player player 1 }
      for player 2 if(fp.x > Screen.width/2){ than use your logic for player player 2 }

      try this solution, it will definitely work. If you have any confusion about how to write that code tell me i will help you with it.

      Delete
    2. okaay i'll give it a try :p you have any social media where i can contact you whose easier to talk ? :p

      Delete
    3. it wont work ;( the players wont move

      Delete
    4. Hi Aaron, Here is an example project i am attaching, hope this helps you solve your problem.
      There are 2 player in the scene, when your touch begins i am casting a ray from camera if the ray hits any of the player than at the end of touch i am checking if its up swipe. Than i am telling the player to do a jump.
      Code is tested so you should not face any issue, just build and test. Later you can implement your own logic.

      http://bit.ly/1fMazPW

      and you can contact me in my email
      sushanta1991@rediffmail.com

      Delete
    5. Hi Aaron, I got your mail, now i understand your issue. To create a multiplayer pong game, you need to write the code a little differently. but you need to follow the same logic of screen.width/2, I am pasting the script below so others can also learn. I already send you the project file. Drag your player1 and player2 to the player array variable in inspector, that's it.

      using UnityEngine;
      using System.Collections;

      public class SwipeSimpleCS : MonoBehaviour {

      public Transform[] player = new Transform[2]; // Drag your players here
      public float speed = 1.0f;
      void Update () {
      for(int i = 0; i < Input.touchCount; i++){
      if(Input.GetTouch(i).position.x < Screen.width/2){
      Vector3 newPosition = player[0].position;
      newPosition.y += Input.GetTouch(i).deltaPosition.y * speed * Time.deltaTime;
      player[0].position = newPosition;
      }
      if(Input.GetTouch(i).position.x > Screen.width/2){
      Vector3 newPosition = player[1].position;
      newPosition.y += Input.GetTouch(i).deltaPosition.y * speed * Time.deltaTime;
      player[1].position = newPosition;
      }
      }
      }
      }

      Delete
  11. I got a quick question, how do i move the object diagonally

    ReplyDelete
  12. " player variable in editor " can somebody elaborate this.....

    ReplyDelete
    Replies
    1. when you add the above script to any gameObject you can see a player variable created in inspector. Drag your player or any gameObject to that variable that you want to rotate using the swipe script given above.

      Delete
  13. Can somoene give me a good jumping code for this? I have one, but my ball jumps infinitly and i want it to just be able to jump once. Thanks in advance!

    ReplyDelete
    Replies
    1. add some drag to your ball, in rigidbody component there is a option for drag, put 1 in there. Than it will not jump infinitly.

      Delete
    2. Didnt work..

      I am jumping in the air and i just want to be able to jump on the ground.

      Here is my code :

      Var jumpHeight = 8;

      {
      rigidbody.velocity.y = jumpHeight;
      }

      Pleasee help :(

      Delete
    3. Previously i thought you want a jumping ball which will gradually slow down, but now i think you just want a simple jump when you swipe up , right ? I build a package for you download it from the below link, build a apk or ipa and do a up swipe and check the result. Hope that helps you.

      http://bit.ly/1kQcnd0

      Delete
    4. It Worked !! Thank you very much man! This blog has really helped me make my game a lot better and I am really gracious. Is there anything I can do for you?

      Delete
    5. Hi man, its me again. I am sorry to bother you, but there's another problem.. The thing is that the OnCollision code make my ball jump once and thats working perfectly , but now I am able to jumps on walls And I want to be able to jump only on Ground. Can you help me make a OnGrounded code to fit in this?

      Delete
    6. Hi Fer Ayon C,
      glad to know my blog is helping you, and to solve your issue you just need to do one thing, tag your ground as "Ground" and leave other objects as it is, and replace the below given code with the previous one that i gave( only for OnCollisionStay ).

      function OnCollisionStay(collisionInfo : Collision) {

      if(collisionInfo.collider.tag == "Ground")
      isFalling=false;
      else
      isFalling=true;

      }

      Delete
    7. I didnt explain myself very well, heres a picture for a better explanation.

      [IMG]http://i60.tinypic.com/2yumt7k.jpg[/IMG]

      Assuming you already saw the picture :
      I want to jump on the blue, and not be able to jump on the red.
      Can you please help me??

      Delete
    8. give "Ground" tag to your green part and give something else to your red part that's it, edit my previous script with the one that i gave in my previous comment. hope that's what you want.

      or if you are saying your don't want to jump at the edges of the platform than do one thing, place an extra collider in the edges(covering your platform edge) and tag it something else, and tag your platform as "Ground", and than do this "(edit my previous script with the one that i gave in my previous comment.)"

      Delete
    9. Are you going to help me ? =( pleasee.

      Delete
    10. Hey Fer sorry dude, i did reply last time, but don't know where the comment went.

      I saw the image, its simple, put a extra collider in the corners/edges and tag it something else than "ground" and use my previoius code and update it with the code given below.

      function OnCollisionStay(collisionInfo : Collision) {

      if(collisionInfo.collider.tag == "Ground")
      isFalling=false;
      else
      isFalling=true;

      }

      it should work, if not tell me i will send you a demo.

      Delete
    11. Thank you very much friend! I'm going to try it tomorrow and tell you the results!

      Delete
    12. Tank you very much, it was so helpful ;)

      Delete
    13. Hello!How to swipe down?!

      Delete
    14. Hello!How to swipe down?!

      Delete
  14. Hi Sushanta,

    Gone Through your description regarding touch directions,Its working Great!

    But I would like to isolate touch on different objects!!I ve used 2d raycast but it is not giving me accurate results.

    Hope to hear from your end.

    Thanks!!

    ReplyDelete
    Replies
    1. Hi Jatin,

      could you please show me your script, i think you are doing some mistake with your 2d raycasting.

      Delete
  15. I need to this logic will apply in 3d so please guide me how to moves object up down left right with using Touch.

    ReplyDelete
    Replies
    1. Hi Jaykumar,
      I need more information about you and what you want to do, than only i can help you. Tell me one thing first, do you have a basic knowledge of unity? do you know how to move object in unity (using keyboard input)?

      Delete
  16. try http://chikkooos.blogspot.jp/2015/02/detecting-swipe-from-unity3d-c-scripts.html

    ReplyDelete
  17. Replies
    1. could you please explain, what you are trying to do ?

      Delete
  18. I wanna script for camera smooth rotation
    I mean the above script rotate camera at 90 angle but what I want is to rotate it according to user force
    please help me

    ReplyDelete
  19. Hi every one
    I want a smooth rotation of camera for my FPS shooter,,i apply the above script but it rotate the player a angle 90,but thats not which i want,,
    i mean the camera rotate with respect to user applied force
    please help me
    im searching for 2 months
    thanks

    ReplyDelete
  20. hi sushanta ? how can i prevent the character from lerping in off lane because he can lerp in side of the terrain which is off lane . i want it to the 3 lane only , thanks .. please reply :)

    ReplyDelete
    Replies
    1. Hi Renz, You just need to put some condition to restrict your player from not falling. like this,

      if(touch.phase == TouchPhase.Ended)
      {
      if((fp.x - lp.x) > 80 && player.position.x > -2) // left swipe
      {
      newLerpPosition = player.position + new Vector3(-2,0,0);
      lerpInAction = true;
      }
      else if((fp.x - lp.x) < -80 && player.position.x < 2) // right swipe
      {
      newLerpPosition = player.position + new Vector3(2,0,0);
      lerpInAction = true;
      }
      else if((fp.y - lp.y) < -80) // up swipe
      {
      tpc.m_Jump = true;
      // add your jumping code here
      }
      }

      Delete
  21. hi sushanta ive been looking for this for months thank you for sharing your knowledge, anyways how can lerp the position of y because i making a prototype flying game but with controls like subway surfer i manage how to add the up and down my only problem is i can seem to make lerp in y axis how can i do this? thank you very much in advance.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to write data to CSV file in UNITY

Hi Guys, if any one is facing problem to save data in csv file can use this solution. If you have any questions, you can ask me through comments.

Things to remember :
Never ever add any commas to your data otherwise, cells will get messed up completely. 


Results :


Here is the code

usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
usingSystem;

publicclassCsvReadWrite : MonoBehaviour {

privateList<string[]> rowData = newList<string[]>();


//Usethisforinitialization
voidStart () {
Save();
    }

voidSave(){

//CreatingFirstrowoftitlesmanually..
string[] rowDataTemp = newstring[3];
rowDataTemp[0] = "Name";
rowDataTemp[1] = "ID";
rowDataTemp[2] = "Income";
rowData.Add(rowDataTemp);

//Youcanaddupthevalues

How to create line graph in unity

Hi guys, previously i have shown how you can create Bar_Graph in unity, after successfully showing bar graph in unity i fell in love with graphs, so when i was asked to show data on a line graph, i got excited and came up with this solution, its almost similar to the bar graph, but this time i have made it more reliable and dynamic.

this is how my setup looks like :




I have an orthographic camera in my scene, which only renders a layer i namded "GUI". and every gameobject in the graph are in "GUI" layer.

why orthographic camera ? its because they easily adjust according to different screen resolutions, i have also used textMesh to show the numbers in graph, which again is the best option if you want to show text in 3d space.


here is a view, how the final graph looks like with data :






in the above image you can see that i am showing data for 99 turns,  but in this small space i cant show data for all the 99 turns, so what i did is i made a dynamic function which give…