2013-06-01 46 views
7

我正在製作一款使用Libgdx的賽車遊戲。我想觸摸屏幕的右半邊以加快速度,同時又不需要移除上一個觸摸點再次觸摸屏幕左側的另一個區域來開槍。我無法檢測到以後的觸摸點。如何跟蹤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(); 
    } 
} 

回答

12

您會想要使用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獲得輸入事件(而不是「輪詢」的輸入作爲上面的例子)。當一個指針進入其中一個區域時,你將不得不跟蹤該指針的狀態(所以如果它離開,你可以清除它)。

+0

嗨,謝謝你的回覆。當我使用你的代碼時,它的觸發點或者是我觸摸屏幕或者不是,但是我只想在觸摸屏幕時觸發這個鏡頭。 –

+4

啊,也許代碼應該在調用'getX(i)'之前檢查'Gdx.input.isTouched(i)'? (可能未使用的觸摸點的X爲零......)。我會更新代碼。 –

+1

嘿,工作,謝謝。 –