Search Unity

swipe motion (left - right - up - down) ??

Discussion in 'iOS and tvOS' started by TouchSoft, Oct 29, 2008.

  1. TouchSoft

    TouchSoft

    Joined:
    Oct 18, 2008
    Posts:
    218
    I would like to add swipe motion in my game to move the camera forward, backward, left, or right .. depending on the swipe motion.

    How can this be coded. Pseudo code is welcomed ... or if you're generous full code snippet :D

    My guess is that I listen for touchBegin and grab the touchPosition ... then listen for touchEnd and grab that touchPosition.

    From there calculate the distance from touchBeginPosition to touchEndPosition on the X and Y axis. If the distance on either axis is greater than a value that I set in the editor... I consider that gesture as a swipe.

    After determining if the gesture is swipe (lets say on the Y axis) I can do:

    Code (csharp):
    1.  
    2. if(touchBeginPositionY > touchEndPositonY)
    3. {
    4.    // This is a swipe going down
    5. }
    6. else
    7. {
    8.    // This is a swipe going up
    9. }
    Is this correct?? Or am I going about this wrong?
     
  2. Thomas-Lund

    Thomas-Lund

    Joined:
    Jan 18, 2008
    Posts:
    465
    You could calculate the vector from start to endpoint - and then see where it points in terms of angle to e.g. a horisontal vector.
     
  3. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Also you might want to take speed into account so that a "move" / "drag" is not perceived as a "swipe".
     
  4. Bael

    Bael

    Joined:
    Jul 21, 2008
    Posts:
    106
    I did something similar, but with mapping moving your finger to the camera's X/Z translation.

    If touch is phase 'moved':
    -Grab touch.positionDelta
    -Multiply it by a custom scroll speed scalar
    -Apply to camera.transform.position

    That ties the camera movement directly to finger dragging (in real-time). If you want to limit it to quick 'swipes' instead of all moves, you could check if the positionDelta is greater than a certain amount before continuing. The problem with the touch.begin / touch.end approach is that you don't register something as a swipe until the action is completed - by checking positionDelta you can flag a swipe as soon as it begins, and control the speed at which movement is considered a 'swipe'.