deano3663
deano3663

Reputation: 99

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

Upvotes: 4

Views: 1675

Answers (1)

durron597
durron597

Reputation: 32343

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
}

Upvotes: 3

Related Questions