Java Reference
In-Depth Information
Listing 8-1. Polling for Key States
public class MyGameCanvas
extends GameCanvas {
Sprite cat;
public MyGameCanvas () {
super(true);
/* Do other setup here */
}
private void moveCat() {
int keyStates = getKeyStates();
int x, y;
x = cat.getX();
y = cat.getY();
if ((keyStates & LEFT_PRESSED) != 0) {
x-=cat.getWidth()/4;
}
if ((keyStates & RIGHT_PRESSED) != 0) {
x+=cat.getWidth()/4;
}
if ((keyStates & UP_PRESSED) != 0) {
y-=cat.getHeight()/4;
}
if ((keyStates & DOWN_PRESSED) != 0) {
y+=cat.getHeight(){/4;
}
cat.setPosition(x,y);
}
/* The rest of the canvas's implementation */
}
Managing Game Execution
Polling for events is all well and good, but just where do you poll for events? You poll in
the game's control loop, which is a separate thread that you can usually implement in the
same class as your GameCanvas , as shown in Listing 8-2.
 
Search WWH ::




Custom Search