Kaer
Kaer

Reputation: 351

How to shoot bullets when space bar is pressed using LibGDX?

I did it as follows:

...
if (Gdx.input.isKeyPressed(Keys.SPACE)) {
   shoot();
}
...

The problem is that if I keep pressing SPACE many bullets are created. What I want is that the bullet is shot only when I press SPACE but not while I'm pressing the key.

Upvotes: 2

Views: 1726

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

Libgdx InputProcessor interface has methods to receive keyDown and keyUp events. This is probably what you should be using.

Upvotes: 7

Zong
Zong

Reputation: 6230

Took a look at the documentation for the library, and it doesn't seem to expose any other way of getting key presses (particularly key down/release). In such a case you can keep track of keep changes yourself with a spaceAlreadyPressed variable that persists between frames.

...
boolean spaceIsPressed = Gdx.input.isKeyPressed(Keys.SPACE);
if (spaceIsPressed && !spaceAlreadyPressed) {
   shoot();
}
...
spaceAlreadyPressed = spaceIsPressed;

It may be safer to use a spaceIsPressed variable in case the input state changes unexpectedly.


Alternatively, if you want to make it shorter, you can use logical laws to reduce to the following, where canShoot also persists between frames and has an initial value of false.

...
canShoot = !canShoot && Gdx.input.isKeyPressed(Keys.SPACE);
if (canShoot) {
   shoot();
}
...

Upvotes: 4

Related Questions