Difference between revisions of "Key Codes"
(Created page with "When keys are pressed and released the computer relays that information in the form of a Key Code number. Common Key Codes used in games are 37, 38, 39 and 40. These are the...") |
|||
| Line 11: | Line 11: | ||
fillRectangle(0,0,640,50); | fillRectangle(0,0,640,50); | ||
setColour("Black"); | setColour("Black"); | ||
| − | print("The key with the code "+e.keyCode+" was pressed | + | print("The key with the code "+e.keyCode+" was pressed.",1,20); |
} | } | ||
eventManager.addEventListener('keydown',printKey); | eventManager.addEventListener('keydown',printKey); | ||
Revision as of 21:13, 14 March 2012
When keys are pressed and released the computer relays that information in the form of a Key Code number.
Common Key Codes used in games are 37, 38, 39 and 40. These are the codes for the arrow keys.
What are the Key Codes for each key.
Run the small program below to find the Key Codes for any key you wish to use.
You can deal with keyboard input in several ways. You can ask, or you can wait to be told.
Asking if a key is down
Asking works best for action games. A game is continually moving and changing based upon a few keys.
You can say if the left arrow key is held held down, move the player left. Which in code could be
if (keyIsDown(37)) playerX=playerX-playerXSpeed;
Waiting to be told
The Key Code reporting program at the top of the page works by waiting.
The function printKey is called whenever a key is pressed down because we have asked for it to be called with the line
eventManager.addEventListener('keydown',printKey);
This means you can respond to any key press when it happens. You will only find out when keys go from up to down however. to find out when keys go from pressed to unpressed, you will need to ask to be told about that as well.
eventManager.addEventListener('keyup',doSomethingElse);
Waiting to be told is a little more complex but works better for things like word processors. You want to know what key was pressed more than just what keys are up or down.