【问题标题】:How to track multiple touch events in Libgdx?如何在 Libgdx 中跟踪多个触摸事件?
【发布时间】:2013-05-28 10:21:21
【问题描述】:

我正在使用 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();
    }
}

【问题讨论】:

    标签: java libgdx multi-touch


    【解决方案1】:

    您需要使用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 来获取输入事件(而不是像上面的示例那样“轮询”输入)。当指针进入其中一个区域时,您必须跟踪该指针的状态(以便在它离开时清除它)。

    【讨论】:

    • 您好,感谢您的回复。当我使用你的代码时,它会触发我是否触摸屏幕,但我只想在触摸屏幕时触发。
    • 啊,也许代码应该在调用getX(i)之前检查Gdx.input.isTouched(i)? (可能未使用的接触点的 X 为零……)。我会更新代码。
    • 简短的例子,很好的解释!谢谢你,先生! :) +1
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多