Game Development Reference
In-Depth Information
Later on, if you wanted to add more features to your game play, using your game
controller, and its support for the KeyCode class's GAME_A ( Jump ), GAME_B
( Fly ), GAME_C ( climb ), and GAME_D ( crawl ) constants, all that you would have to
do is to add these new features into your game would be to add another four Boolean
variables (jump, fly, climb, and crawl) to the up, down, left, and right at the top of the
screen, and add in another four case statements.
These four W (UP), S (DOWN), A (LEFT), and D (RIGHT) case statements, once
added to the switch statement, would bring your KeyEvent object and its event hand-
ling Java code structure to only a dozen lines of Java code. Your new
.setOnKeyPressed() event handling structure would look like this block of code after
you make this modification:
scene .setOnKeyPressed (KeyEvent event ) -> {
switch ( event .getCode()) {
case UP: up = true; break;
case DOWN: down = true; break;
case LEFT: left = true; break;
case RIGHT: right = true; break;
case W:
up
= true; break;
case S:
down = true; break;
case A:
left = true; break;
case D:
right = true; break;
}
});
As you can see, now the user can use either set of keys, or both sets of keys at the
same time, to control the game play. Now that you have made the .setOnKeyPressed()
event handling structure more flexible (and powerful) for the game player, let's do the
same thing to the .setOnKeyReleased() event handling structure, which will instead set
a false value to the up, down, left and right Boolean flag variables when the user has
released the A or LEFT, W or UP, S or DOWN, or D or RIGHT keys on the keyboard,
remote control, or device keyboard and keypad.
Your .setOnKeyReleased() event handling Java code should look like the following
once you add these case statements at the end of the body of the switch statement:
scene .setOnKeyReleased (KeyEvent event ) -> {
switch ( event .getCode()) {
case UP: up = false; break;
case DOWN: down = false; break;
Search WWH ::




Custom Search