Key Codes

From CodeStuff
Revision as of 19:35, 14 May 2016 by Lerc (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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.[edit]

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[edit]

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;

Have a look at DrawTrail for a very simple drawing program using the keyboard.

Waiting to be told[edit]

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.