简体   繁体   中英

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.

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

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();
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM