Java Reference
In-Depth Information
This is attractive for games because it gives your application more control. Instead of
waiting for the system to invoke the key callback methods in Canvas , you can immediately find
out the state of the device keys.
The returned integer uses one bit to represent each of the nine game actions. A one bit
indicates a key press, while a zero bit indicates no key press. Each of the bits is represented by
a constant in the GameCanvas class as shown in Table 14-1.
Table 14-1. Game Action Bit Constants in GameCanvas
GameCanvas Bit Constants
Corresponding GameCanvas Action Constants
UP_PRESSED
UP
DOWN_PRESSED
DOWN
LEFT_PRESSED
LEFT
RIGHT_PRESSED
RIGHT
FIRE_PRESSED
FIRE
GAME_A_PRESSED
GAME_A
GAME_B_PRESSED
GAME_B
GAME_C_PRESSED
GAME_C
GAME_D_PRESSED
GAME_D
By grabbing the current state of the keys (a technique called polling ), you can respond to
user actions within the game loop instead of relying on the event callback methods, which run
in a different thread. You could expand the example GameCanvas loop presented earlier as
follows to respond to key presses:
Graphics g = getGraphics();
while(true) {
// Check for user input.
int ks = getKeyStates();
if ((ks & UP_PRESSED) != 0)
moveUp();
else if ((ks & DOWN_PRESSED) != 0)
moveDown();
// ...
// Update game state.
// Draw stuff using g.
flushGraphics();
}
If you're still paying attention, you're probably wondering what happens when the user
presses and releases a key between the times when your application calls getKeyStates() . The
key states are latched , which means that a key press sets the corresponding bit and makes it
Search WWH ::




Custom Search