KeyHandling

One day computers will be controlled with the power of our minds. Until that point in time, the main way of interacting with the computer is via the keyboard and mouse.

Keyhandling differs between browsers, therefore Gamma provides some convenience methods that the game developer can use to create keybindings that work across different browsers. This is provided by the gma.keyHandler object.

How to use it

The register function allows you to register a function to be called, when a particular button is pressed.

Note

You need to register against a keycode – like ‘65’, rather than ‘a’ – so a list of common keycodes is listed at the end of this page.

When the button is pressed (or released), the function will be called with the event object that is generated by the keypress. This event object can used to determine whether the key was pressed or released.

gma.keyHandler.register(65, function(event) {
    if (event.type==="keyup") {
        alert('You pressed a');
    }
});

The keyHandler also has reset and numEvents functions. The reset function can be used to remove all previously registered bindings and the numEvents method will give you the number of bindings registered for a particular key.

// This will say 0 because nothing is registered for code 70 yet
alert(gma.keyHandler.numEvents(70));

// Set a binding for the 'e' button
gma.keyHandler.register(70, function(event) { alert('You pressed e');});

// Now it will say 1 because we just registered one
alert(gma.keyHandler.numEvents(70));

// Remove all currently registered bindings
gma.keyHandler.reset()

// And it will say 0 again, because we removed all the bindings
alert(gma.keyHandler.numEvents(70));

KeyCodes

Cursor Keys

Key Code
Cursor Left 37
Cursor Down 40
Cursor Right 39
Cursor Up 38

KeyPad

Key Code
0 -> 9 96 -> 105
. 110
Enter 13
/ 111
* 106
- 109
+ 107

Modifiers

Key Code
Shift 16
Ctrl 17
Alt 18

Special Keys

Key Code
BackSpace 8
Tab 9
Enter 13
Caps Lock 20
Esc 27
SpaceBar 32
Delete 46
Page Up 33
Page Down 34
End 35
Home 36
Insert 45
Windows Key 92
F1 -> F12 112 -> 123

Formatting

Key Code
` and ~ 192
- and _ 189
= and + 187
\ and | 220

Numbers and Letters

Key Code
0 -> 9 48 -> 57
a -> z 65 -> 90
Fork me on GitHub