Game Development Reference
In-Depth Information
key-typed event or CHAR_UNDEFINED for a key-pressed or key-released event.
Character input is only reported for key-typed events, since key-pressed and key-re-
leased events are not necessarily associated with character input. Therefore, the charac-
ter variable is guaranteed to be meaningful only for key-typed events. In a sense, by not
using key-typed events, we are saving both memory and CPU processing, by not hav-
ing to process this Unicode character variable.
For key-pressed and key-released KeyEvent objects, the code variable in the
KeyEvent class will contain your KeyEvent object's keycode, defined using the
KeyCode class you learned about earlier. For key-typed events, this code variable al-
ways contains the constant KeyCode.UNDEFINED . So as you can see, key-pressed
and key-released are thus designed to be used differently than key-typed, and that's the
reason we are using these for our game event handling.
Key-pressed and key-released events are low-level, and depend upon platform or
keyboard layout. They are generated whenever a given key is pressed or released, and
are the only way to “poll” the keys that do not generate character input. The key being
pressed or released is indicated by the code variable, which contains a virtual
KeyCode.
Adding Keyboard Event Handling:
Using KeyEvents
I think that is enough background information for us to move on to implementing
KeyEvent processing for the game, so add a line of code after your screen WIDTH and
HEIGHT constant declarations, and declare four Boolean variables named up , down ,
left , and right , using a single compound declaration statement, shown in Figure 9-9 .
Since the default value for any Boolean value is false (which will signify a key which
is not being pressed, that is, a key which is currently released), we do not have to expli-
citly initialize these variables. This is done by using the following line of Java code,
which is also shown error-free at the top of Figure 9-9 :
boolean up, down, left, right;
 
Search WWH ::




Custom Search