Search code examples
javaandroidlibgdx

How can i end a touchDragged with firing touchUp? LibGDX


What i am trying to do is move a rectangle left and right by dragging my finger on my android device. I want the rectangle to stop when i stop without lifting up my finger. Is this possible?

My InputHandler code:

 @Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    lastTouch.set(screenX, screenY);
    return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    // Determines if my finger is moving to the left or right
    Vector2 newTouch = new Vector2(screenX, screenY);
    Vector2 delta = newTouch.cpy().sub(lastTouch);

    // Moves the player right
    if(delta.x > 0f) {
        world.getPlayer().setVel(5.0f, 0f);
    } else {
        // Moves the player left
        if(delta.x < 0f) {
            world.getPlayer().setVel(-5.0f, 0);
        }
        // This is not being called
        else
            world.getPlayer().setVel(0f, 0f);
    }

    lastTouch = newTouch;
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    world.getPlayer().setVel(0f, 0f);
    return false;
}

Solution

  • The problem is when you touchDrag the input is never exactly the pixel where the finger is on because touch screens are not pixel accurate. Your finger hits the screen at multiple pixels at the same time. The device then decides which pixel is sent to the application.

    So a possible solution is to add a minimum delta which must be reached to move the player at all. If the minimum delta is not reached stop movement.

    if(delta.x > 20f) {
            world.getPlayer().setVel(5.0f, 0f);
        } else {
            // Moves the player left
            if(delta.x < -20f) {
                world.getPlayer().setVel(-5.0f, 0);
            }
            // This is not being called
            else
                world.getPlayer().setVel(0f, 0f);
        }
    

    In this case minimum delta is 20. You need to play around which value fits your needs.