如何通过触发touchUp结束touchDragged? LibGDX

时间:2016-12-22 02:39:23

标签: java android libgdx

我想要做的是通过在我的Android设备上拖动手指来左右移动一个矩形。当我停下而不抬起手指时,我希望矩形停止。这可能吗?

我的InputHandler代码:

 @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;
}

1 个答案:

答案 0 :(得分:0)

问题是当你触摸拖拉时,输入绝不是手指所在的像素,因为触摸屏不是像素精确的。您的手指同时以多个像素点击屏幕。然后,设备决定将哪个像素发送到应用程序。

所以一个可能的解决方案是添加一个必须达到的最小增量来移动玩家。如果未达到最小增量停止运动。

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);
    }

在这种情况下,最小增量为20.您需要围绕哪个值来满足您的需求。