Search code examples
javalibgdx

libGDX How to stop touchUp registering if user moves finger after touch down


I have a scrollPane with several actors inside. each actor has a touch event registered to set a new screen, but users will obviously want to be able to scroll through the list of actors without the touches registering. how do I go about this? the actors are registering touch events as below...

public boolean touchDown(InputEvent event, float x, float y, int pointer, int button){
    octave3Btn.getColor().a = 0.25f;
    return true;
}
public void touchUp(InputEvent event, float x, float y, int pointer, int button){
    octave3Btn.getColor().a = 1f;
    launcher.setScreen(new ListNotesScreen(NoteNameAssets.octave3NoteNameArray,ImageAssets.octave3BtnTextureArray,manager, launcher));
}

Solution

  • Use the touchDragged callback to know whether there was a drag in between, or not.

    private boolean wasDragged = false;
    
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        octave3Btn.getColor().a = 0.25f;
        wasDragged = false;
        return true;
    }
    
    public boolean touchDragged(InputEvent event, float x, float y, int pointer) {
        // you can use a simple flag here, or better calculate the distance
        // and set the flag when the distance surpassed a certain limit
        wasDragged = true;
    }
    
    public boolean touchUp(InputEvent event, float x, float y, int pointer, int button) {
        octave3Btn.getColor().a = 1f;
        if (!wasDragged) {
            launcher.setScreen(new ListNotesScreen(...));
        }
    }
    

    This should probably take small errors into account. You would probably not set the flag in case there was a drag event for 1px. Better calculate the distance that the touch was dragged in between touchDown and touchUp and then switch the screen in case distance < 10 for example.