key presses

We have already seen examples where the camera is controlled by a combination of mouse clicks and key presses. Many simulations require that the mouse and keyboard be used for additional purposes, for instance, to pull a trigger or activate a door.

Keyboard and mouse events are detected by writing functions to detect them, and telling the browser when they are to be invoked. The basic set of events is listed below.

There are some additional higher level events as well, which you can research on the web, namely onkeypress, onclick, and ondblclick. The exact implementation of these seems to vary across browsers, making them trickier to implement reliably.

Here is an example of a simple key press handler.

function onKeyDown(evt) {
  switch (evt.keyCode) {
    case 82: // 'r'
    rPressed = true; break;

Note that we figure out which key is pressed by checking a key code. A full list of JavaScript key codes is available many places on the web, such as here. In order for the event handling function to be called at the right time, it must be installed.

window.addEventListener('keydown', onKeyDown, false );

The above line installs the onKeyDown function to listen for key presses in the window.

example 6: key presses