This site requires JavaScript, please enable it in your browser!
Greenfoot back
chipmunkrage
chipmunkrage wrote ...

2019/10/17

How to make a character shoot ONCE every time a key gets pressed?

chipmunkrage chipmunkrage

2019/10/17

#
Currently making a game where when the user presses "k", the character shoots, but keeps shooting as long as the button is down. How would I make it so the character only shoots once, even when the key is held down? I'm using isKeyDown("k") to determine when he shoots. Thanks!
danpost danpost

2019/10/17

#
chipmunkrage wrote...
when the user presses "k", the character shoots, but keeps shooting as long as the button is down. How would I make it so the character only shoots once, even when the key is held down? I'm using isKeyDown("k") to determine when he shoots.
Track the state of the key. When the saved value does not match the current state of the key, then there was a change in its state. Update the value saved and if the change put the key in a pressed state, shoot. Example code follows:
// outside act
private boolean kDown;

// inside act
if (kDown != Greenfoot.isKeyDown("k"))
{
    kDown = !kDown;
    if (kDown) shoot();
}
The code inside act can be short-handedly written as:
if (kDown != Greenfoot.isKeyDown("k") && (kDown = !kDown)) shoot();
chipmunkrage chipmunkrage

2019/10/18

#
Thank you! This worked great.
You need to login to post a reply.