Search code examples
javaandroidlibgdxbox2d

LibGDX How to recognize a gestureswipe?


I'm working with an app that will show different cases. You either swipe right or left depending on what your choice is. The drag thing is working but the problem is to know when the object has been swiped and dropped to the direction you want. How should I continue?
(Similar to the tinder app)

public class SimpleGestureDetector extends GestureDetector {


public interface DirectionListener {
    void onLeft();

    void onRight();

    void onUp();

    void onDown();
}

public SimpleGestureDetector(DirectionListener directionListener) {
    super(new DirectionGestureListener(directionListener));
}

private static class DirectionGestureListener extends com.badlogic.gdx.input.GestureDetector.GestureAdapter {
    DirectionListener directionListener;

    public DirectionGestureListener(DirectionListener directionListener){
        this.directionListener = directionListener;
    }

    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
        if(Math.abs(velocityX)>Math.abs(velocityY)){
            if(velocityX>0){
                directionListener.onRight();
            }else{
                directionListener.onLeft();
            }
        }else{
            if(velocityY>0){
                directionListener.onDown();
            }else{
                directionListener.onUp();
            }
        }
        return super.fling(velocityX, velocityY, button);
    }

}

}

How the appscreen looks like:

  stage = new Stage();
    SimpleGestureDetector sgd = new SimpleGestureDetector(new SimpleGestureDetector.DirectionListener() {

        @Override
        public void onUp() {
            leaf.setY(leaf.getY()+100);
        }

        @Override
        public void onRight() {
            leaf.setX(leaf.getX()+100);

            }
        }

        @Override
        public void onLeft() {
            leaf.setX(leaf.getX()-100);
        }

        @Override
        public void onDown() {
            leaf.setY(leaf.getY()-100);
        }


    });

Solution

  • When user is dragging his finger across the screen your pan method is called. So when dragging starts your method will get x and y coordinates of the finger. You should remember them when pan is called for the first time. Use some bool variable, called "firstCall" or somethig so when pan is called, check for it and set from true to false...

    Then, when user lift his finger your panStop will be called. Again, you'll receive x and y coordinates. So compare those with those you remembered before and do some basic math. i.e. if old y is almost the same as new y it means swipe was horizontal. And if new x is greater old x it means swipe was to the right. Something like that.

    https://github.com/libgdx/libgdx/wiki/Gesture-detection