I'm trying to make a pong game, but the movement is clunky; there is a slight delay whenever I hold down a key to make a paddle move.
For example, I'll hold a key, the paddle will move once, and then it will take a second before it begins moving again continuously.
I'm told that this is a feature of the OS, not of Java; however, I would still like to find a workaround in Java so that the movement is smooth and continuous from the beginning, without having to wait for the OS to begin autopressing the key.
Can someone help? (I've tried booleans and keylisteners and "while" loops, but these did not work for me. A passage taken from one of these failed attempts is written below:)
root.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP: paddle1Up = true;
break;
case DOWN: paddle1Down = true;
break;
case W: paddle2Up = true;
break;
case S: paddle2Down = true;
break;
}
}
});
root.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP: paddle1Up = false;
break;
case DOWN: paddle1Down = false;
break;
case W: paddle2Up = false;
break;
case S: paddle2Down = false;
break;
}
}
});
root.requestFocus();
primaryStage.setTitle("Pong");
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest((event)->System.exit(0));
primaryStage.show();
// This is the main animation thread
new Thread(() -> {
while (true) {
sim.evolve(1.0);
while (paddle1Up){
sim.movePaddle(sim.getPaddle1(), 0, -1);
}
while (paddle1Down){
sim.movePaddle(sim.getPaddle1(), 0, 1);
}
while (paddle2Up){
sim.movePaddle(sim.getPaddle2(), 0, -1);
}
while (paddle2Down){
sim.movePaddle(sim.getPaddle2(), 0, 1);
}
Platform.runLater(()->sim.updateShapes());
try {
Thread.sleep(25);
} catch (InterruptedException ex) {
}
}
}).start();
}