0

I am working on a game that relies on the player's keyboard input. The current implementation registers whether a key is currently pressed or not.

However, I would like to implement a system in which the player has to do a full key press in order to increment the game state. For example, they'd have to press and release 'A' in order to move to the next position. Then press and release the button to move on again, and so forth. Holding the button down should not result in moving forward.

Here is a very simplified version of what I've got right now:

int velocityX = 0;

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_A) {ActiveA = true;}
}
    
public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_A) {ActiveA = false;}
}

public void tick() {    
    x += velocityX; 
    if (ActiveA){velocityX = 5; }
    else if (!ActiveA){velocityX = 0; } 
}

The game class calls tick() at about 60 times a second, so X constantly increments while the key is pressed but not while the key is released.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Does this answer your question? [How to stop repeated keyPressed() / keyReleased() events in Swing](https://stackoverflow.com/questions/1736828/how-to-stop-repeated-keypressed-keyreleased-events-in-swing) – gameshack_ Jan 04 '22 at 19:59
  • Don't use `KeyListener`, use the [Key Bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) instead. You need another state manager, which can register which keys have been released (you can assume a release was preceded by a press) and which can be cleared by your main loop each time it runs – MadProgrammer Jan 04 '22 at 20:52

1 Answers1

0

By adding another variable that is set TRUE only when the player releases the key, we can set velocity to 5 for one tick, then set that variable false so it doesn't keep repeating.

int velocityX = 0;
boolean ActiveA = false;
boolean didFullPress = false;

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    
    if (key == KeyEvent.VK_A) {
        ActiveA = true;
    } 
}
    
public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_A && ActiveA) {
        ActiveA = false;
        didFullPress = true;
    } 
}

public void tick() {    
    x += velocityX; 
    if (didFullPress){
        velocityX = 5 
        didFullPress = false;
    }
    else {velocityX = 0 } 
}
Ewan Brown
  • 640
  • 3
  • 12