In my code, when detecting an arrow key the character will move accordingly. This is done through a Timer and TimerTask to schedule "movements" of the character. However, when another key is pressed it causes the character to flip around and malfunction completely. I am looking for a way to stop the user from pressing any keys on the keyboard, until the character is finished moving.
My code is as follows:
@FXML
public void moveCharacter(KeyEvent event) {
switch (event.getCode()){
case D, RIGHT:
try {
moveForward();
} catch (URISyntaxException | InterruptedException e) {
throw new RuntimeException(e);
}
break;
case A, LEFT:
try {
moveBack();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
break;
}
}
Initially, I thought to use a timer to prevent keyboard input after a set amount of time. This was done like so:
final long THRESHOLD = 1_500_000_000L;
private long lastMoveNanos;
long now = System.nanoTime();
if (lastMoveNanos <= 0L || now - lastMoveNanos >= THRESHOLD) {
//switch case here
}
lastMoveNanos = now;
However, it didn't work and my character still malfunctioned. I had also used Thread.sleep within the switch case, but it just stopped my character from moving and teleported it to the destination.
Thank you in advance for any sort of advice.