
|
November 2004
|
|
|
If your MIDlet uses the MIDP 2.0 GameCanvas class, it can take advantage of the features that this class offers, not only the handling of graphics, but also the handling of key presses. Using GameCanvas.getKeyState() is an active way of getting the key status as opposed to the passive Canvas.keyPressed(int keyState) callback method. The getKeyState() method is often recommended for a number of reasons, one being that it fits better in a standard game's main loop than callback methods do. However, MIDP 1.0 MIDlets are stuck with Canvas and the callback methods it offers. One difficulty that this brings is responding to, and even knowing when, the user keeps a key pressed. The trick is, that the callback method only will be called (as its name suggests) at the moment when a key is pressed. As long as the key isn't released and pressed again, there will only be one single callback invocation of keypressed(). This is usually not what you want in a MIDlet; you often want the user's character to keep moving as long as the key is pressed. "Perfect!" you may think, and begin using keyRepeated instead of keyPressed. However, as soon as you try your new MIDlet, you'll find that it just might not be so "perfect" after all. The keyRepeated works like the repeat functionality on a computer keyboard. That means that there will be a pause before the keyRepeated gets called for the first time, which isn't appropriate for a MIDlet game. And in addition to that, the longer you keep the key pressed, the method will be called with shorter and shorter intervals. So, what to do? The easiest way is really quite straightforward; you'll rely on the callback methods keyPressed() and keyReleased() to set boolean flags that indicate whether keys are pressed or not. The flag for the key is set to "true" in keyPressed() and to "false" in keyReleased. In your main game loop, you can then check the flag: as long as the flag for a specific key is set to "true", you know that the key is still pressed, even if keyPressed() is not called more than once. Click on the link below to download a simple MIDlet that shows both techniques; joystick "up" and "down" will be handled by the boolean flags, while "left" and "right" will be handled with keyRepeated(). Note the different behavior: KeyRepeated() makes a slow start but will accelerate, while the boolean flags work smoothly and predictably. | |
Copyright © 2001 - 2009 Sony Ericsson Mobile Communications AB. All Rights Reserved.