The more the I think about it, the more I can't see a way to write good keyboard control in Java on Linux. Let me explain:-
Say you are writing a basic shoot'em-up. AFAIK, there are basically two ways to control the players sprite when your interface is the KeyPressed and KeyReleased events: you can either have the actual movement code inside these events, such as:
public void keyPressed(KeyEvent e) {
if (e == Key_UP) {
ship.y_pos++;
}
}
The problem with this way is that the ship will move as fast as the keyboard repeat rate, regardless of the main game loop or anything.
The other way (and the way I'm doing it in my game) is to store which keys are currently pressed (in a boolean array), and then process them in the game loop, such as:-
public void keyPressed(KeyEvent e) {
keys_pressed[e.getKeyCode()] == true;
}
(and set it to false on the KeyRelease as well).
public void gameLoop() {
while (true) {
if (keys_pressed[KEY_UP] == true) {
ship.y_pos++;
}
// Rest of game code here
}
}
The flaw with this, as I mentioned, is that if the player holds down a key, then with so many keypress/release events being fired for the duration it is held down, the key might not be marked as being pressed at the time when the keys are being processed in the main game loop.
Can anyone tell me what I'm missing? Or should I just move to another language?
No comments:
Post a Comment