拖动手指离开后仍会调用 ImageButton 触摸事件
ImageButton touch event still called after dragging finger away
我的 LibGDX 游戏中有一个 ImageButton 有一个小错误,可能会惹恼用户。如果我按下按钮,但决定不想点击它,我会把手指拖开。
但是,即使我的手指在将它拖走后不再位于 ImageButton 之上,仍然会调用 touchUp()
方法。
如何阻止 touchUp 事件的发生?
我不知道以某种方式获取该 ImageButton 的边界(如何进行)并查看 touchUp 位置是否对应是否可行。我已经尝试查找它,但到目前为止我还没有找到任何东西,因为我的问题非常具体。
这是我初始化按钮的方式:
retryButton = new ImageButton(getDrawable(new Texture("RetryButtonUp.jpg")), getDrawable(new Texture("RetryButtonDown.jpg")));
retryButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
if(touchable) {
game.setScreen(new PlayScreen(game, difficulty));
dispose();
}
}
});
您应该使用 ClickListener
而不是 InputListener
,并且不要覆盖 touchUp
方法,而是覆盖 clicked
方法。
扩展 grimrader22 的答案,我还建议使用 ClickListener 来处理触摸事件,但即使您拖动 touchUp
事件中的代码,您仍然会遇到同样的问题ImageButton 之外的手指,这就是 clicked
方法应该正常工作的原因。
但是,如果您想使用 touchUp
和 touchDown
方法,请看这里:touchUp
和 touchDown
中的 x 和 y 值代表本地ImageButton 上触摸事件的坐标。因此,简单的解决方案是确保 touchUp
方法中事件的 x 和 y 都在 ImageButton 的局部坐标内...
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
boolean inX = x >= 0 && x < getWidth();
boolean inY = y >= 0 && y < getHeight();
if(inX && inY && touchable) {
game.setScreen(new PlayScreen(game, difficulty));
dispose();
}
}
我的 LibGDX 游戏中有一个 ImageButton 有一个小错误,可能会惹恼用户。如果我按下按钮,但决定不想点击它,我会把手指拖开。
但是,即使我的手指在将它拖走后不再位于 ImageButton 之上,仍然会调用 touchUp()
方法。
如何阻止 touchUp 事件的发生?
我不知道以某种方式获取该 ImageButton 的边界(如何进行)并查看 touchUp 位置是否对应是否可行。我已经尝试查找它,但到目前为止我还没有找到任何东西,因为我的问题非常具体。
这是我初始化按钮的方式:
retryButton = new ImageButton(getDrawable(new Texture("RetryButtonUp.jpg")), getDrawable(new Texture("RetryButtonDown.jpg")));
retryButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
if(touchable) {
game.setScreen(new PlayScreen(game, difficulty));
dispose();
}
}
});
您应该使用 ClickListener
而不是 InputListener
,并且不要覆盖 touchUp
方法,而是覆盖 clicked
方法。
扩展 grimrader22 的答案,我还建议使用 ClickListener 来处理触摸事件,但即使您拖动 touchUp
事件中的代码,您仍然会遇到同样的问题ImageButton 之外的手指,这就是 clicked
方法应该正常工作的原因。
但是,如果您想使用 touchUp
和 touchDown
方法,请看这里:touchUp
和 touchDown
中的 x 和 y 值代表本地ImageButton 上触摸事件的坐标。因此,简单的解决方案是确保 touchUp
方法中事件的 x 和 y 都在 ImageButton 的局部坐标内...
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
boolean inX = x >= 0 && x < getWidth();
boolean inY = y >= 0 && y < getHeight();
if(inX && inY && touchable) {
game.setScreen(new PlayScreen(game, difficulty));
dispose();
}
}