I'm building a Pacman game, so basically I have to wait for the user to enter a key before moving Pacman. I'm waiting for an input before drawing my new canvas with the movement done, but I'm stuck on the line where I have to wait the entry.
public void something(){
//do something
wait until a key is pressed
if( key pressed is an arrow key){
something();
}else{
wait for the key to be pressed
}
}
I've been told to use something like setFocusTraversable(true) and requestFocus(). Is it relevant? Thanks.
EDIT:
public void afficher(Labyrinth labyrinth) {
Pane root = new Pane() {
@Override
protected void layoutChildren() {
GraphicsContext gc = canvas.getGraphicsContext2D();
canvas.setWidth(sceneWidth);
canvas.setHeight(sceneHeight);
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
canvas.setOnKeyPressed((KeyEvent t) -> {
// I think that's the point of the keyevent
switch (t.getCode()) {
case UP:
labyrinth.movePacman(control.Direction.Up);
break;
case DOWN:
labyrinth.movePacman(control.Direction.Down);
break;
case RIGHT:
labyrinth.movePacman(control.Direction.Right);
break;
case LEFT:
labyrinth.movePacman(control.Direction.Left);
break;
}
});
drawGame(gc, labyrinth);
}
};
root.getChildren().add(canvas);
Scene scene = new Scene(root, sceneWidth, sceneHeight);
primaryStage.setTitle("Pacman");
primaryStage.setScene(scene);
primaryStage.setResizable(false); // empeche de modifier la taille de la fenetre
primaryStage.show();
}
And now for the controller who calls this function
public class ControllerFX extends Application {
Labyrinth labyrinth = new Labyrinth();
@Override
public void start(Stage primaryStage) {
VueFX vuefx = new VueFX(primaryStage);
vuefx.afficher(labyrinth);
do{
//I think that's the part where I've to be in the loop
}while(Labyrinth.getLives() > 0 || Labyrinth.getAmountOfGhosts() > 0);
Labyrinth.gameOver();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}