简体   繁体   中英

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.

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;
    }
}

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
}

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