按住KeyEvent时,如何仅一次? [英] How do I the KeyEvent only once when it is held down?
问题描述
我正在尝试以一定的速度射击导弹,但是目前您可以简单地按住发射按钮(太空),它将连续制造一列导弹.
I am trying to shoot a missile at a certain rate but currently you can simple hold down the fire button (Space) and it will make a continuous line of missiles.
我相信这是因为KeyEvent
是在您按住KeyEvent
时触发的,而我要做的只是在按住它时触发一次.
I believe this is because the KeyEvent
is being triggered when you hold it down when what I need it to do is only trigger once when you hold it down.
我如何使它检测到仅按下一次按钮就被按下?
How would I make it detect the holding down of a button as only pressing it once?
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_A) {
dx = -1;
}
if (key == KeyEvent.VK_D) {
dx = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
}
if (key == KeyEvent.VK_A) {
dx = 0;
}
if (key == KeyEvent.VK_D) {
dx = 0;
}
}
推荐答案
只需添加一个检查以确保您已释放密钥,然后再允许自己启动即可.我使用 AtomicBoolean
以确保不会因触发不同事件而产生多线程问题.
Just add a check to make sure you've released the key before allowing yourself to fire again. I use AtomicBoolean
to ensure there are no multithreading issues by the different events getting fired.
private final AtomicBoolean canShoot = new AtomicBoolean(true);
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
if (canShoot.compareAndSet(true, false)) {
fire();
}
}
// snip
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
canShoot.set(true);
}
// snip
}
这篇关于按住KeyEvent时,如何仅一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!