Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Swipe help please

Discussion in 'iOS and tvOS' started by snicholls, May 10, 2010.

  1. snicholls

    snicholls

    Joined:
    Mar 19, 2009
    Posts:
    229
    I have looked and looked for examples and it would be great if someone would be able to just make a small script to show how to do this.

    I would like to know how to detect swipes, left right up and down if possible. I have noticed people seem reluctant to show any code (I have no idea why) and the scripts I can find are a bit over the top it seems.
     
  2. imparare

    imparare

    Joined:
    Jun 24, 2008
    Posts:
    369
  3. groovfruit

    groovfruit

    Joined:
    Apr 26, 2010
    Posts:
    257
    *sigh* Why is the JS source of swipe code so elusive? We are developing for iPhone are we not? Can anyone from Unity help. I appreciate the C# versions, but no idea how to implement them into my app that is all JS (and all that I know in limited programming skills).

    Swipe left > do something
    Swipe right > do something

    Thats all i need to figure out.

    The only thing I've found in JS so far that works is this (sorry can't find the Unity forum link for it to credit it:

    Code (csharp):
    1.  
    2.  
    3. var smoothingConstant = .01; // Speed of ending-swipe
    4.  
    5. //private var layerMask = 1 << 11; // Only check for collisions in TouchManager layer
    6. private var hit : RaycastHit; // Hit variable
    7. private var joystickId : int; // Stores which finger is on the joystick
    8. private var previousTouch : iPhoneTouch; // Stores the previous touch
    9. private var endedTouch = false; // Informs when the touch has ended
    10.  
    11. private var velocity : float; // Velocity
    12. private var time : float; // Time
    13. private var acceleration : float; // Acceleration
    14.  
    15.  
    16.  
    17. var test : GameObject;
    18.  
    19. function Update () {
    20.     for (var touch : iPhoneTouch in iPhoneInput.touches) {
    21.        // Draw a ray from the camera to the touch position
    22.        var ray : Ray = Camera.main.ScreenPointToRay (touch.position);
    23.        // If the touch is new, and it is on the joystick, then store the touch in joystickId
    24.        if (touch.phase == iPhoneTouchPhase.Began  touch.position.x < 150) {
    25.           joystickId = touch.fingerId;
    26.          
    27.      }
    28.        // If the finger is not on the joystick, check to see if it hits the "able to swipe" area. If so, then call the swipe function
    29.        // Note -- the collision is a box, with rendering removed in layer 11. It is the child of the parent, and is the appropriate size.
    30.         if (touch.phase != iPhoneTouchPhase.Ended  touch.phase == iPhoneTouchPhase.Moved) {
    31.         // if (Physics.Raycast (ray, hit, layerMask)) {
    32.             if (endedTouch)
    33.                previousTouch = touch;
    34.              
    35.             Swipe(touch);
    36.             previousTouch = touch;
    37.             endedTouch = false;
    38.             Instantiate(test);
    39.            
    40.            
    41.          
    42.        }
    43.        // If the finger doing the swipe has been removed, then reset all the variables
    44.        else if (touch.phase == iPhoneTouchPhase.Ended) {
    45.           endedTouch = true;
    46.           velocity = 0;
    47.           time = 0;
    48.          
    49.        }
    50.        // If the touch ended, smooth it out
    51.        if (endedTouch == true) {
    52.           if ( velocity != 0)
    53.              SmoothEnding();    
    54.       }
    55.        
    56.    }
    57. }
    58.  
    59. // Swipe function
    60. function Swipe ( touch : iPhoneTouch ) {
    61.    // Temporary variables
    62.    var deltaTouch : float = (touch.position.x - previousTouch.position.x);
    63.    var initialTime = time;
    64.    var initialVelocity = deltaTouch/(time);
    65.    
    66.    // Stored variables
    67.    time += Time.deltaTime;
    68.    velocity = deltaTouch/(time);
    69.    acceleration = (velocity - initialVelocity)/(time - initialTime);
    70.    
    71.    // Transform the position with respect to acceleration
    72.    //transform.Rotate(0, -deltaTouch * Time.deltaTime, 0);
    73.    transform.Rotate(0, velocity * Time.deltaTime, 0);
    74.    Debug.Log("Acceleration =" + acceleration + " and Velocity = " + velocity);
    75. }
    HOWEVER, I can't for the life of me figure out how to change/add to this code to detect swipe direction.

    Any help greatly appreciated... I've been hogging these forums tonight with this issue hoping to find some assistance somewhere!
     
  4. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    The basic routine is:-

    - On the touch start phase, record the position and the time and set a boolean value to say that a swipe might be happening.

    - Each frame during the drag phase, check that the finger doesn't stray too far from a straight line (horizontal or vertical, depending on the swipe type). If it does stray, cancel the boolean flag to denote it isn't a swipe.

    - On the end phase, again, record the time and position and subtract the initial time and position. If the time is greater than the maximum swipe time or the distance is less than the minimum swipe distance, or the boolean flag is false then it's not a swipe. Otherwise, it is.

    Annoyingly, I can't test the following code on a device at the moment, but it should at least give you an idea. This is for a vertical swipe, but you can get a horizontal swipe by changing touch.position.y for touch.position.x, etc.
    Code (csharp):
    1. var startTime: float;
    2. var startPos: Vector2;
    3. var couldBeSwipe: boolean;
    4. var comfortZone: float;
    5. var minSwipeDist: float;
    6. var maxSwipeTime: float;
    7.  
    8.  
    9. function Update() {
    10.     if (iPhoneInput.touchCount > 0) {
    11.         var touch = iPhoneInput.touches[0];
    12.        
    13.         switch (touch.phase) {
    14.             case iPhoneTouchPhase.Began:
    15.                 couldBeSwipe = true;
    16.                 startPos = touch.position;
    17.                 startTime = Time.time;
    18.                 break;
    19.            
    20.             case iPhoneTouchPhase.Moved:
    21.                 if (Mathf.Abs(touch.position.y - startPos.y) > comfortZone) {
    22.                     couldBeSwipe = false;
    23.                 }
    24.                 break;
    25.            
    26.             case iPhoneTouchPhase.Stationary:
    27.                 couldBeSwipe = false;
    28.                 break;
    29.            
    30.             case iPhoneTouchPhase.Ended:
    31.                 var swipeTime = Time.time - startTime;
    32.                 var swipeDist = (touch.position - startPos).magnitude;
    33.                
    34.                 if (couldBeSwipe  (swipeTime < maxSwipeTime)  (swipeDist > minSwipeDist)) {
    35.                     // It's a swiiiiiiiiiiiipe!
    36.                     var swipeDirection = Mathf.Sign(touch.position.y - startPos.y);
    37.                    
    38.                     // Do something here in reaction to the swipe.
    39.                 }
    40.                 break;
    41.         }
    42.     }
    43. }
     
  5. groovfruit

    groovfruit

    Joined:
    Apr 26, 2010
    Posts:
    257
    Thanks for this.

    This script looks a lot cleaner than the one I've 'hacked' together to get things working.

    I'll take a look.... Thanks for your help :)
     
  6. spentak

    spentak

    Joined:
    Feb 11, 2010
    Posts:
    246
    So this swipe detection is great, but how do I move an object based upon the distance and direction of the swipe? I need to move a camera (in any direction, its a top down 2d game) based upon the length and direction of the swipe. Then it should slow down, then stop moving. The camera should also move while the finger is dragging. Any thoughts?
     
  7. cheezorg

    cheezorg

    Joined:
    Jun 5, 2008
    Posts:
    394
  8. col000r

    col000r

    Joined:
    Mar 27, 2008
    Posts:
    698
    Also not exactly what you're looking for, but similar: SwipeControl (GameAssets.net)
     
  9. saurabh

    saurabh

    Joined:
    Sep 9, 2010
    Posts:
    70
    SWIPE WITH TOUCH........THIS REALLY WORKS.......... TRY IT


    ///////////////////////////////////////////////
    code:-
    /////////////////////////////////////////////
    using UnityEngine;
    using System.Collections;

    public class Touch
    {
    public iPhoneTouch touch1;
    public Vector2 Start_pos;
    public float time1;

    }


    public class swipe : MonoBehaviour {

    ArrayList ar=new ArrayList();
    float x_dir,y_dir;
    // Use this for initialization
    void Start () {

    }
    Vector2 end_pos,start_pos;
    GameObject txt;
    TextMesh tm;
    // Update is called once per frame
    void Update () {

    txt=GameObject.Find("New Text");

    //tm=txt.GetComponent(typeof(TextMesh)) as TextMesh;

    //txt.transform.position=pos;

    GameObject c=GameObject.Find("Cube");
    foreach(iPhoneTouch touch in iPhoneInput.touches)
    {



    if(touch.phase==iPhoneTouchPhase.Began)



    {
    Vector2 temp=camera.WorldToScreenPoint(c.transform.position);

    Vector2 t=touch.position;



    if(temp.x+25>t.x temp.x-25<t.x)
    {

    if(temp.y+25>t.y temp.y-25<t.y )
    {

    Touch ob =new Touch();
    ob.time1=(float)Time.time;
    ob.touch1=touch;
    ob.Start_pos=t;
    ar.Add(ob);
    }

    }


    }

    if(touch.phase==iPhoneTouchPhase.Ended)
    {
    for(int i=0;i<ar.Count;i++)
    {

    Touch ob=(Touch)ar;
    if(ob.touch1.fingerId==touch.fingerId)
    {
    float time_end=(float)Time.time;

    if((time_end-ob.time1)<1)
    {
    end_pos=touch.position;

    /*if(end_pos.x>ob.Start_pos.x)
    {

    x_dir=(end_pos.x-(end_pos.x-ob.Start_pos.x));
    }
    else
    {
    x_dir=ob.Start_pos.x-(ob.Start_pos.x-end_pos.x);
    }


    if(end_pos.y>ob.Start_pos.y)
    { y_dir=end_pos.y-(end_pos.y-ob.Start_pos.y);
    }
    else
    {
    y_dir=ob.Start_pos.y-(ob.Start_pos.y-end_pos.y);
    }*/
    // float dir=Mathf.Atan2((end_pos.y-ob.Start_pos.y),(end_pos.x-ob.Start_pos.x));
    c.rigidbody.AddForce((end_pos.x-ob.Start_pos.x)*10,(end_pos.y-ob.Start_pos.y)*10,0);
    //tm.text=iPhoneInput.touchCount);
    ar.RemoveAt(i);
    }}


    }



    }

    }





    }

    //
    //void t1(iPhoneTouch t2)
    //
    //{
    //
    //if(t2.phase==iPhoneTouchPhase.)
    //{
    //
    //
    //
    //
    // }
    //
    // }

    }
     
  10. saurabh

    saurabh

    Joined:
    Sep 9, 2010
    Posts:
    70
    //////////////////////////////////
    SWIPE WITH TOUCH

    //////////////////////////////////

    using UnityEngine;
    using System.Collections;

    public class Touch
    {
    public iPhoneTouch touch1;
    public Vector2 Start_pos;
    public float time1;

    }


    public class swipe : MonoBehaviour {

    ArrayList ar=new ArrayList();
    float x_dir,y_dir;
    // Use this for initialization
    void Start () {

    }
    Vector2 end_pos,start_pos;
    GameObject txt;
    TextMesh tm;
    // Update is called once per frame
    void Update () {

    txt=GameObject.Find("New Text");

    //tm=txt.GetComponent(typeof(TextMesh)) as TextMesh;

    //txt.transform.position=pos;

    GameObject c=GameObject.Find("Cube");
    foreach(iPhoneTouch touch in iPhoneInput.touches)
    {



    if(touch.phase==iPhoneTouchPhase.Began)



    {
    Vector2 temp=camera.WorldToScreenPoint(c.transform.position);

    Vector2 t=touch.position;



    if(temp.x+25>t.x temp.x-25<t.x)
    {

    if(temp.y+25>t.y temp.y-25<t.y )
    {

    Touch ob =new Touch();
    ob.time1=(float)Time.time;
    ob.touch1=touch;
    ob.Start_pos=t;
    ar.Add(ob);
    }

    }


    }

    if(touch.phase==iPhoneTouchPhase.Ended)
    {
    for(int i=0;i<ar.Count;i++)
    {

    Touch ob=(Touch)ar;
    if(ob.touch1.fingerId==touch.fingerId)
    {
    float time_end=(float)Time.time;

    if((time_end-ob.time1)<1)
    {
    end_pos=touch.position;

    /*if(end_pos.x>ob.Start_pos.x)
    {

    x_dir=(end_pos.x-(end_pos.x-ob.Start_pos.x));
    }
    else
    {
    x_dir=ob.Start_pos.x-(ob.Start_pos.x-end_pos.x);
    }


    if(end_pos.y>ob.Start_pos.y)
    { y_dir=end_pos.y-(end_pos.y-ob.Start_pos.y);
    }
    else
    {
    y_dir=ob.Start_pos.y-(ob.Start_pos.y-end_pos.y);
    }*/
    // float dir=Mathf.Atan2((end_pos.y-ob.Start_pos.y),(end_pos.x-ob.Start_pos.x));
    c.rigidbody.AddForce((end_pos.x-ob.Start_pos.x)*10,(end_pos.y-ob.Start_pos.y)*10,0);
    //tm.text=iPhoneInput.touchCount);
    ar.RemoveAt(i);
    }}


    }



    }

    }





    }

    //
    //void t1(iPhoneTouch t2)
    //
    //{
    //
    //if(t2.phase==iPhoneTouchPhase.)
    //{
    //
    //
    //
    //
    // }
    //
    // }

    }
     
  11. Bampf

    Bampf

    Joined:
    Oct 21, 2005
    Posts:
    369
    I recently posted a working example on my blog of getting a UnityGUI list to scroll up and down in response to swipes. I walk through it a piece at a time, so I am hopeful that someone interested in handling swipes in general could learn from it.

    The code is in C#, but it should be easy to port, the code is mostly if-then statements, numeric assignments, and comparisons.

    http://www.mindthecube.com/blog/2010/09/adding-iphone-touches-to-unitygui-scrollview
     
    Westland likes this.
  12. schwertfisch

    schwertfisch

    Joined:
    Sep 7, 2010
    Posts:
    126
    Thanks for the easily understandable code andeeee. :)
    I applied the code on a game object and that's supposed to make an iTween movement as a reaction to the swipe. I get the following error though:
    Assets/scripts/SwipeScript.js (14,36): BCE0020: An instance of type 'UnityEngine.Touch' is required to access non static member 'phase'.
    What does this mean? :-/
     
  13. schwertfisch

    schwertfisch

    Joined:
    Sep 7, 2010
    Posts:
    126
    ok I'd made a typo at the referred line and that caused the error - I apologise...

    Just one thing: what values for comfortZone and minSwipeDist (in andeeee's script) would you recommend?

    Also: shouldn't the if condition in line 21, check to see if (touch.position.x - startPos.x) > comfortZone) for a vertical swipe?

    I tried a large range of values (beginning from the obvious - I think - around 50 to100) but I get to achieve a swipe veeery difficult (I set the maxSwipeTime to a very large value to make sure my swipe speed is not the problem). That's strange.
     
    Last edited: Nov 29, 2010
  14. schwertfisch

    schwertfisch

    Joined:
    Sep 7, 2010
    Posts:
    126
    (Regarding andeeee's script)
    I modified the script in a way that I avoid everything that has to do with the couldBeSwipe: boolean and strangely enough it works great.
    Thanks so much andeeee, I was searching and searching and the script you suggested (with a few tiny modifications) did my job perfectly!!!
     
  15. prangya_p

    prangya_p

    Joined:
    Jul 6, 2010
    Posts:
    10
    Hi schwertfisch ,,

    can u post that script for vertical swipe?
     
  16. kapilkundan

    kapilkundan

    Joined:
    Dec 21, 2010
    Posts:
    52
    How can find the Direction of swipe Like Right to left Vice -Verse and Up to Bottom
     
  17. schwertfisch

    schwertfisch

    Joined:
    Sep 7, 2010
    Posts:
    126
    prangya_p and kapilundan, I'm really sorry for not having responded for so long, I hadn't visited the thread and I wasn't notified that there were replies to it (maybe I could change this from my settings), I guess my answer is not so useful after 50 days but I'm posting it anyway as it could be useful to others at least...

    I use the following script, that is attached to my character (something like a chess pawn) and will move it on a board horizontally or vertically, depending on the swipes. The swipes can be made anywhere on the screen and you don't have to make them on the character.


    var comfortZoneVerticalSwipe: float = 50; // the vertical swipe will have to be inside a 50 pixels horizontal boundary
    var comfortZoneHorizontalSwipe: float = 50; // the horizontal swipe will have to be inside a 50 pixels vertical boundary
    var minSwipeDistance: float = 14; // the swipe distance will have to be longer than this for it to be considered a swipe
    //the following 4 variables are used in some cases that I don’t want my character to be allowed to move on the board (it’s a board game)
    var allowGoUp: boolean = true;
    var allowGoRight: boolean = true;
    var allowGoLeft: boolean = true;
    var allowGoDown: boolean = true;


    function Update () {
    if (Input.touchCount >0) {
    var touch = Input.touches[0];

    switch (touch.phase) { //following are 2 cases
    case TouchPhase.Began: //here begins the 1st case
    startPos = touch.position;
    startTime = Time.time;

    break; //here ends the 1st case



    case TouchPhase.Ended: //here begins the 2nd case
    var swipeTime = Time.time - startTime;
    var swipeDist = (touch.position - startPos).magnitude;
    var endPos = touch.position;

    if ((Mathf.Abs(touch.position.x - startPos.x))<comfortZoneVerticalSwipe (swipeTime < maxSwipeTime) (swipeDist > minSwipeDistance) Mathf.Sign(touch.position.y - startPos.y)>0 !moving transform.position.z<3 allowGoUp)
    {
    //... then go up
    moving=true;
    [code here, to make character move the way you want (upwards)]
    }


    if ((Mathf.Abs(touch.position.x - startPos.x))<comfortZoneVerticalSwipe (swipeTime < maxSwipeTime) (swipeDist > minSwipeDistance) Mathf.Sign(touch.position.y - startPos.y)<0 !moving transform.position.z>-3 allowGoDown)
    {
    //... then go down
    moving=true;
    [code here, to make character move the way you want (downwards)]
    }


    if ((Mathf.Abs(touch.position.y - startPos.y))<comfortZoneHorizontalSwipe (swipeTime < maxSwipeTime) (swipeDist > minSwipeDistance) Mathf.Sign(touch.position.x - startPos.x)<0 !moving transform.position.x>-2 allowGoLeft)
    {
    //... then go left
    moving=true;
    [code here, to make character move the way you want (to the left)]
    }

    if ((Mathf.Abs(touch.position.y - startPos.y))<comfortZoneHorizontalSwipe (swipeTime < maxSwipeTime) (swipeDist > minSwipeDistance) Mathf.Sign(touch.position.x - startPos.x)>0 !moving transform.position.x<2 allowGoRight)
    {
    //...then go right
    moving=true;
    [code here, to make character move the way you want (to the right)]
    }
    break; //here ends the 2nd case

    }
    }
     
  18. kapilkundan

    kapilkundan

    Joined:
    Dec 21, 2010
    Posts:
    52
    Hey matt thank !!
     
  19. CameronB999

    CameronB999

    Joined:
    Sep 11, 2010
    Posts:
    20
    Hey Everyone,

    I thought I'd post this in case anyone was looking for a C# version of a swipe script. I converted Andee's into it and made a few modifications:

    1) IPhoneTouch class is deprecated, so I converted it to use Input.Touches (I think someone did this earlier in javascript)

    2) When determining the swipe distance, for strict vertical swipes I wanted it to only take the Y values into consideration.

    3) The comfort zone comparison should be with touch.position.x not touch.position.y, so I fixed that.

    4) I created an enumeration for the swipe direction. The direction, along with the swipe time are exposed as public variables, lastSwipe and lastSwipeTime respectfully. You can toss this script on an empty game object and access those values from other scripts to determine vertical swipes.

    5) I also put in some debug messages to assist with fine tuning the comfort zone.

    It should be pretty easy to modify for horizontal swipes too. Since I have to do that, I will probably post that soon as well.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class SwipeDetector : MonoBehaviour {
    6.  
    7.     // Values to set:
    8.     public float comfortZone = 70.0f;
    9.     public float minSwipeDist = 14.0f;
    10.     public float maxSwipeTime = 0.5f;
    11.  
    12.     private float startTime;
    13.     private Vector2 startPos;
    14.     private bool couldBeSwipe;
    15.    
    16.     public enum SwipeDirection {
    17.         None,
    18.         Up,
    19.         Down
    20.     }
    21.    
    22.     public SwipeDirection lastSwipe = SwipeDetector.SwipeDirection.None;
    23.     public float lastSwipeTime;
    24.    
    25.     void  Update()
    26.     {
    27.         if (Input.touchCount > 0)
    28.         {
    29.             Touch touch = Input.touches[0];
    30.        
    31.             switch (touch.phase)
    32.             {
    33.                 case TouchPhase.Began:
    34.                     lastSwipe = SwipeDetector.SwipeDirection.None;
    35.                                         lastSwipeTime = 0;
    36.                     couldBeSwipe = true;
    37.                     startPos = touch.position;
    38.                     startTime = Time.time;
    39.                     break;
    40.                
    41.                 case TouchPhase.Moved:
    42.                     if (Mathf.Abs(touch.position.x - startPos.x) > comfortZone)
    43.                     {
    44.                         Debug.Log("Not a swipe. Swipe strayed " + (int)Mathf.Abs(touch.position.x - startPos.x) +
    45.                                   "px which is " + (int)(Mathf.Abs(touch.position.x - startPos.x) - comfortZone) +
    46.                                   "px outside the comfort zone.");
    47.                         couldBeSwipe = false;
    48.                     }
    49.                     break;
    50.                 case TouchPhase.Ended:
    51.                     if (couldBeSwipe)
    52.                     {
    53.                         float swipeTime = Time.time - startTime;
    54.                         float swipeDist = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude;
    55.                    
    56.                         if ((swipeTime < maxSwipeTime)  (swipeDist > minSwipeDist))
    57.                         {
    58.                             // It's a swiiiiiiiiiiiipe!
    59.                             float swipeValue = Mathf.Sign(touch.position.y - startPos.y);
    60.                        
    61.                             // If the swipe direction is positive, it was an upward swipe.
    62.                             // If the swipe direction is negative, it was a downward swipe.
    63.                             if (swipeValue > 0)
    64.                                 lastSwipe = SwipeDetector.SwipeDirection.Up;
    65.                             else if (swipeValue < 0)
    66.                                 lastSwipe = SwipeDetector.SwipeDirection.Down;
    67.                        
    68.                             // Set the time the last swipe occured, useful for other scripts to check:
    69.                             lastSwipeTime = Time.time;
    70.                             Debug.Log("Found a swipe!  Direction: " + lastSwipe);
    71.                         }
    72.                     }
    73.                     break;
    74.             }
    75.         }
    76.     }
    77. }
    78.  
     
    joaomorais likes this.
  20. gypsy fly

    gypsy fly

    Joined:
    Mar 31, 2011
    Posts:
    36
    Hummm, I also need a swipe in Unity.

    How about an implementation of iOS native UIGestureRecognizer with the following subclasses: UITapGestureRecognizer [Pinch, Rotation, Swipe, Pan, LongPress]?

    I haven't looked yet, but I gather it's not in Unity, right?
     
  21. LimeSplice

    LimeSplice

    Joined:
    Jul 15, 2011
    Posts:
    111
    There's a lot of errors in this code - how did you get it to work?
     
  22. helios

    helios

    Joined:
    Oct 5, 2009
    Posts:
    308
  23. markpollard1

    markpollard1

    Joined:
    Apr 1, 2010
    Posts:
    70
    This is the C# code i am using Thanks for sharing yours i was able to get mine going too

    Code (csharp):
    1.  
    2. public float comfortZoneVerticalSwipe = 50; // the vertical swipe will have to be inside a 50 pixels horizontal boundary
    3.         public float comfortZoneHorizontalSwipe = 50; // the horizontal swipe will have to be inside a 50 pixels vertical boundary
    4.         public float minSwipeDistance = 14; // the swipe distance will have to be longer than this for it to be considered a swipe
    5.             //the following 4 variables are used in some cases that I don’t want my character to be allowed to move on the board (it’s a board game)
    6.         public float startTime;
    7.         public Vector2 startPos;
    8.         public float maxSwipeTime;
    9.  
    10. void Update(){
    11. if (Input.touchCount >0) {
    12.         Touch touch = Input.touches[0];
    13.  
    14.         switch (touch.phase) { //following are 2 cases
    15.                
    16.         case TouchPhase.Began: //here begins the 1st case
    17.             startPos = touch.position;
    18.             startTime = Time.time;
    19.  
    20.             break; //here ends the 1st case
    21.            
    22.         case TouchPhase.Ended: //here begins the 2nd case
    23.             float swipeTime = Time.time - startTime;
    24.             float swipeDist = (touch.position - startPos).magnitude;
    25.            
    26.  
    27.             if ((Mathf.Abs(touch.position.x - startPos.x))<comfortZoneVerticalSwipe  (swipeTime < maxSwipeTime)  (swipeDist > minSwipeDistance)  Mathf.Sign(touch.position.y - startPos.y)>0)
    28.             {
    29.                 if(playerY > 0 )
    30.                 {
    31.                     playerY --;
    32.                     player.transform.position = LevelCreator.gridPositionArray[playerX,playerY];
    33.                     CheckMine();
    34.                 }
    35.                
    36.                 print("up");
    37.             }
    38.  
    39.  
    40.             if ((Mathf.Abs(touch.position.x - startPos.x))<comfortZoneVerticalSwipe  (swipeTime < maxSwipeTime)  (swipeDist > minSwipeDistance)  Mathf.Sign(touch.position.y - startPos.y)<0)
    41.             {
    42.                 if(playerY < LevelCreator.gridHeight -1)
    43.                 {
    44.                     playerY ++;
    45.                     player.transform.position = LevelCreator.gridPositionArray[playerX,playerY];
    46.                     CheckMine();
    47.                 }
    48.                
    49.                 print("down");
    50.             }
    51.  
    52.  
    53.             if ((Mathf.Abs(touch.position.y - startPos.y))<comfortZoneHorizontalSwipe  (swipeTime < maxSwipeTime)  (swipeDist > minSwipeDistance)  Mathf.Sign(touch.position.x - startPos.x)<0)
    54.             {
    55.                 if(playerX > 0)
    56.                 {
    57.                     playerX --;
    58.                     player.transform.position = LevelCreator.gridPositionArray[playerX,playerY];
    59.                     CheckMine();
    60.                 }
    61.                
    62.                 print("left");
    63.             }
    64.  
    65.             if ((Mathf.Abs(touch.position.y - startPos.y))<comfortZoneHorizontalSwipe  (swipeTime < maxSwipeTime)  (swipeDist > minSwipeDistance)  Mathf.Sign(touch.position.x - startPos.x)>0)
    66.             {
    67.                 if(playerX < LevelCreator.gridWidth -1)
    68.                 {
    69.                     playerX ++;
    70.                     player.transform.position = LevelCreator.gridPositionArray[playerX,playerY];
    71.                     CheckMine();
    72.                 }
    73.                
    74.                 print("right");
    75.                
    76.             }
    77.             break; //here ends the 2nd case
    78.             }
    79.     }
    80. }
    81.  
    82.  
     
    blejdea likes this.
  24. Crunx

    Crunx

    Joined:
    Jan 2, 2011
    Posts:
    28
    Hello All,

    I am still in the new stages of Unity but I am having soo much trouble with getting touch going on. So I used this code and attached it to my Character (who is a stationary character). I then proceed to build it to my Virtual Andriod phone, everything seems good but It doesn't seem to detect my touch!

    Any code I've used soo far has been this problem, is there any way to start testing me touch code? I haven't been able to write any yet because I am not sure if my virtual phone is even taking it ok...

    I'm sure this code works, but how will I know what it'll do once I put it on my phone? Unless there is another way to do touch detecting on the editor rather than on a virtual device? Please let me know if you.


    Thanks!
     
  25. captainbacon

    captainbacon

    Joined:
    May 22, 2013
    Posts:
    11
    Create a lablel and output the info in it. Than test it on your phone.
     
  26. Darren Wong

    Darren Wong

    Joined:
    Nov 14, 2012
    Posts:
    4
    its work! thx u...
    by the way, how to make it much more smoother?
     
  27. jays99485

    jays99485

    Joined:
    Nov 2, 2014
    Posts:
    4
    Hi,

    I want to play animations (left,right,up,down) on swipe ,that i did in Maya software .but i am not able to play , i really appreciate if anyone can help me. please find the below script. Im new to scripting , please tell me what am i doing wrong.

    using UnityEngine; using System.Collections; using UnityEngine.UI;

    public class PlayerControllerScript : MonoBehaviour {

    1. publicfloat speed =1;// speed in meters per second
    2. publicfloat smooth =2.0F;
    3. privateVector2 fp;// first finger position
    4. privateVector2 lp;// last finger position
    5. privatefloat horizontalMovement;
    6. privatefloat verticalMovement;
    7. voidStart()
    8. {
    9. animation.Play("idle");
    10. }
    11. // Update is called once per frame
    12. voidUpdate(){
    13. Vector3 moveDir =Vector3.zero;
    14. foreach(Touch touch inInput.touches)
    15. {
    16. if(touch.phase ==TouchPhase.Began)
    17. {
    18. fp = touch.position;
    19. lp = touch.position;
    20. }
    21. if(touch.phase ==TouchPhase.Moved)
    22. {
    23. lp = touch.position;
    24. if((fp.x - lp.x)>80)// left swipe
    25. {
    26. animation.Play("left");
    27. }
    28. elseif((fp.x - lp.x)<-80)// right swipe
    29. {
    30. animation.Play("right");
    31. }
    32. elseif((fp.y - lp.y)<-80)// up swipe
    33. {
    34. animation.Play("up");
    35. }
    36. elseif((fp.y - lp.y)>80)// down swipe
    37. {
    38. animation.Play("down");
    39. }
    40. }
    41. if(touch.phase ==TouchPhase.Ended)
    42. {
    43. verticalMovement =0;
    44. horizontalMovement =0;
    45. }
    46. }
    47. float tiltAroundY =0;
    48. if(!isDecive)
    49. {
    50. moveDir.x =Input.GetAxis("Horizontal");// get result of AD keys in X
    51. moveDir.x =Input.GetAxis("Horizontal");
    52. moveDir.y =Input.GetAxis("Vertical");// get result of WS keys in Y
    53. moveDir.y =Input.GetAxis("Vertical");
    54. // move this object at frame rate independent speed:
    55. tiltAroundY =Input.GetAxis("Horizontal")* tiltAngle;
    56. }
    57. else
    58. {
    59. moveDir.x = horizontalMovement;// get result of AD keys in X
    60. moveDir.y = verticalMovement;// get result of WS keys in Y
    61. }
    62. }
     
  28. mujaffars

    mujaffars

    Joined:
    Jan 18, 2016
    Posts:
    1
    Hey @CameronB999 I have attached your script to Game object but it is not working

    not displaying message in console

    Steps I have followed

    -- Created new Unity 2d project
    -- Created new game object
    -- Applied your script to that object
    -- Run the project

    -- Tried to swap by using mouse on object
    -- Checked console

    But nothing displayed in console

    Am I missing anything or doing something wrong

    Please help
     
  29. louisb200

    louisb200

    Joined:
    Sep 5, 2017
    Posts:
    1
    how can i do this for android? cant seem to find a way that works
     
  30. tradititionallimb

    tradititionallimb

    Joined:
    Feb 12, 2019
    Posts:
    1

    Would you attach the code to the player or a separate game object