Search code examples
c#androidunity-game-enginetouch

How can I get the swipe direction in android when coding a game in Unity3d engine?


This game plays correctly in the editor, with up and down arrows. When I built it for android, any touch makes the player jump. A downward swipe should cause a slide instead. The general idea of the touch direction came from another Q&A somewhere on the web, but obviously it's not working.

This is all in the Update() method of my PlayerController MonoBehaviour

//Check for Swipe Direction
if (Input.touchCount > 0) 
{
    theTouch = Input.GetTouch(0);
    if(theTouch.phase == TouchPhase.Began)
    {
        touchStartPosition = theTouch.position;
    }
    if(theTouch.phase == TouchPhase.Ended)
    {
        touchEndPosition = theTouch.position;
        swipeDirection = (int) (touchEndPosition.y - touchStartPosition.y); //probably should have named this swipeDirectionY, but swipeDirectionX won't be used in this game.
    }            
}

Then I have:

//JUMP
if ((Input.GetKeyDown(KeyCode.UpArrow) || (Input.touchCount > 0 && swipeDirection > 0 )) && isOnGround)
{/*JUMP CODE HERE*/}

and:

//SLIDE
if ((Input.GetKeyDown(KeyCode.DownArrow) || (Input.touchCount > 0 && swipeDirection < 0)) && isOnGround)
{/*SLIDE CODE HERE*/} 

Solution

  • Make sure setting swipeDirection to 0 whenever player jump/slide. If not, it will keep repeating last swipe even if you don't move/swipe. Because touchCount will be positive in the moment you touch again and you will already have swipeDirection value that's not equal to 0.