[英]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. 问题是,如果我一直按下SPACE,就会创建许多子弹。 What I want is that the bullet is shot only when I press SPACE but not while I'm pressing the key.
我想要的是,只有当我按下SPACE时弹出子弹,但是当我按下键时弹出。
Libgdx InputProcessor
interface has methods to receive keyDown
and keyUp
events. Libgdx
InputProcessor
接口具有接收keyDown
和keyUp
事件的方法。 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. 在这种情况下,您可以使用在帧之间保留的
spaceAlreadyPressed
变量spaceAlreadyPressed
跟踪保持更改。
...
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. 如果输入状态意外更改,则使用
spaceIsPressed
变量可能更安全。
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
也可以在帧之间保持并且初始值为false
。
...
canShoot = !canShoot && Gdx.input.isKeyPressed(Keys.SPACE);
if (canShoot) {
shoot();
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.