如何在Libgdx中跟踪多个触摸事件?

8

我正在使用Libgdx制作一款赛车游戏。我希望触摸屏幕右半部分来加速,同时不需要移除之前的触摸点,在屏幕左侧再次触摸以发射子弹。我无法检测到后续的触摸点。

我已经搜索并获得了Gdx.input.isTouched(int index)方法,但无法确定如何使用它。我的屏幕触摸代码如下:

if(Gdx.input.isTouched(0) && world.heroCar.state != HeroCar.HERO_STATE_HIT){
    guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    if (OverlapTester.pointInRectangle(rightScreenBounds, touchPoint.x, touchPoint.y)) {
       world.heroCar.state = HeroCar.HERO_STATE_FASTRUN;
       world.heroCar.velocity.y = HeroCar.HERO_STATE_FASTRUN_VELOCITY;
    }
} else {
    world.heroCar.velocity.y = HeroCar.HERO_RUN_VELOCITY;
}

if (Gdx.input.isTouched(1)) {
    guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    if (OverlapTester.pointInRectangle(leftScreenBounds, touchPoint.x, touchPoint.y)) {
       world.shot();
    }
}
1个回答

14
你需要使用 Gdx.input.getX(int index) 方法。整数 index 参数表示活动指针的ID。为了正确使用它,您需要迭代所有可能的指针(以防两个人在平板上有20个手指)。类似于这样的代码:
boolean fire = false;
boolean fast = false;
final int fireAreaMax = 120; // This should be scaled to the size of the screen?
final int fastAreaMin = Gdx.graphics.getWidth() - 120;
for (int i = 0; i < 20; i++) { // 20 is max number of touch points
   if (Gdx.input.isTouched(i)) {
      final int iX = Gdx.input.getX(i);
      fire = fire || (iX < fireAreaMax); // Touch coordinates are in screen space
      fast = fast || (iX > fastAreaMin);
   }
}

if (fast) {
   // speed things up
} else {
   // slow things down
}

if (fire) {
   // Fire!
}

另一种方法是设置一个InputProcessor来获取输入事件(而不是像上面的例子那样“轮询”输入)。当指针进入其中一个区域时,您需要跟踪该指针的状态(以便在其离开时清除它)。


嗨,感谢您的回复。当我使用您的代码时,它会在我触摸屏幕或不触摸屏幕时都发射子弹,但我只想在触摸屏幕时才发射子弹。 - Vishal Singh
4
啊,也许在调用getX(i)之前,代码应该检查Gdx.input.isTouched(i)?(可能未使用的触摸点的X坐标为零...)。我会更新代码。 - P.T.
短小的例子,解释得很好!谢谢,先生! :) +1 - Willi Mentzel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接