Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make LibGDX detect only a single tap/click?

I'm trying to do a basic counter, so every tap will increase a counter by one. I can get the counter to work but it's also increasing the count crazily when I hold down my finger/click.

Code:

public void render() {
    boolean isTouched = Gdx.input.isTouched();

    if (isTouched) {
        System.out.println(Cash);
        Cash++;

    }

}

Also, while I'm here, how can you print an integer/float that will change every tap?

Like: font.draw(batch, Cash, 300, 260);

Straight up don't work.

like image 358
CodingNub Avatar asked Dec 08 '25 22:12

CodingNub


2 Answers

What you are doing is polling the Input. But for what you want, an InputProcessor would be the way to go:

public class MyInputProcessor implements InputProcessor {
   @Override
   public boolean keyDown (int keycode) {
      return false;
   }

   @Override
   public boolean keyUp (int keycode) {
      cash++; //<----
      return false;
   }

   @Override
   public boolean keyTyped (char character) {
      return false;
   }

   @Override
   public boolean touchDown (int x, int y, int pointer, int button) {
      return false;
   }

   @Override
   public boolean touchUp (int x, int y, int pointer, int button) {
      return false;
   }

   @Override
   public boolean touchDragged (int x, int y, int pointer) {
      return false;
   }

   @Override
   public boolean touchMoved (int x, int y) {
      return false;
   }

   @Override
   public boolean scrolled (int amount) {
      return false;
   }
}

Set it in your create code:

MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);

Reference: Libgdx Wiki Event-Handling

how can you print an integer/float that will change every tap?
Like: font.draw(batch, Cash, 300, 260);
Straight up don't work.

BitmapFont#draw accepts a String, not an int/float. You must use one of these:

Integer.toString(Cash); //or
Float.toString(Cash);

Pro Tip: Don't start a variable name with Caps. it should be cash.

like image 114
Lestat Avatar answered Dec 11 '25 13:12

Lestat


The InputProcessor is definitely the way to go longer term (event-based input is more robust, I think), but a built-in hack you can also use is the "justTouched" API:

if (Gdx.input.justTouched()) {
    System.out.println(Cash);
    Cash++;
}

See https://code.google.com/p/libgdx/wiki/InputPolling

like image 38
P.T. Avatar answered Dec 11 '25 13:12

P.T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!