Search Unity

Touch Direction and Keep direction

Discussion in 'Scripting' started by sujitha304, Aug 8, 2019.

  1. sujitha304

    sujitha304

    Joined:
    Apr 15, 2018
    Posts:
    5
    So i created small script which identifies the direction of a touch swipe and keeps that direction till you move to another direction or let go of your finger.Thought of sharing



    Code (CSharp):
    1.  
    2. public float touchThreshold = 0.3f;
    3. Direction tocuhDirction;
    4. enum Direction
    5.     {
    6.         right = 1,
    7.         left = -1,
    8.         noDirction = 0
    9.     }
    10. void update(){
    11. if (Input.touchCount != 0)
    12.         {
    13.             if (Input.touches[0].phase == TouchPhase.Began)
    14.             {
    15.                 initialTouch = Input.touches[0];
    16.             }
    17.             else if (Input.touches[0].phase == TouchPhase.Moved || tocuhDirction != Direction.noDirction)
    18.             {
    19.                 float deltaX = Input.touches[0].position.x - initialTouch.position.x;
    20.                 if (deltaX > touchThreshold || tocuhDirction == Direction.right)
    21.                 {
    22.                     tocuhDirction = Direction.right;
    23.                     //do whatever you want here
    24.  
    25.                 }
    26.                 if (deltaX < -touchThreshold || tocuhDirction == Direction.left)
    27.                 {
    28.                     tocuhDirction = Direction.left;
    29.                     //do whatever you want here
    30.                 }
    31.             }
    32.  
    33.         }
    34. }
     
    Last edited: Aug 17, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    CAUTION: If you think you are implementing the Update() method in a Monobehavior, the above script is not implementing that method. Did you just retype all this in?!
     
  3. sujitha304

    sujitha304

    Joined:
    Apr 15, 2018
    Posts:
    5
    i just typed it in my bad i just thought this would make it easier to copy paste it to quickly test it:rolleyes: