8

I am making a racing game using Libgdx. I want to touch the half right side of screen to speed up, at the same time without removing previous touch point touch again another on the left side of the screen to fire a shot. I am unable to detect later touch points.

I have searched and get Gdx.input.isTouched(int index) method, but cannot determin how to use it. My screen touch code is:

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 Answer 1

14

You'll want to use the Gdx.input.getX(int index) method. The integer index parameter represents the ID of an active pointer. To correctly use this, you will want to iterate through all the possible pointers (in case two people have 20 fingers on the tablet?).

Something like this:

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!
}

An alternative approach is to setup an InputProcessor to get input events (instead of "polling" the input as the above example). And when a pointer enters one of the areas, you would have to track that pointer's state (so you could clear it if it left).

3
  • Hi, thanks for your reply. When i used your code its fire the shot either i touch the screen or not but i want to fire the shot only when screen touch. Jun 3, 2013 at 15:01
  • 4
    Ah, maybe the code should check Gdx.input.isTouched(i) before invoking getX(i)? (Probably unused touch points have an X of zero...). I'll update the code.
    – P.T.
    Jun 3, 2013 at 16:44
  • short example, well explained! thank you, sir! :) +1 Feb 25, 2017 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.