Source code for this sketch

Using the Keyboard

Similar to the mouse, your sketch can interact with the keyboard via functions and built-in variables. You can customize the code for the following functions:

  • keyPressed()
  • keyReleased()
  • keyTyped()
  • keyIsDown()

The following built-in variables give you access to what is typed on the keyboard:

  • keyIsPressed (a Boolean variable indicating if a key is pressed right now)
  • key (regular characters)
  • keyCode (special keys like the arrows)

There are a lot of special tricks involved with using the keyboard because the keyboard is also used by other apps that may be running on your computer. You will probably have to experiment with small example sketches to find out how to make the keyboard do what you want, and you should consult the reference manual. Here are some things to watch out for:

  • Arrow keys may make your whole canvas move around on your web page. To avaoid this, add the command "return false;" (without the quotation marks) to the end of any of the key... functions.
  • The keyTyped() function works best with the key variable. This function ignores the non-character keys like Ctrl, Alt, and the arrow keys, but it WILL apply the shift key appropriately so that key can contain upper or lower case characters and the special characters above the numbers. The function will also repeat if a key is held down.

Your assignment is to create a sketch in your portfolio that makes use of the keyboard. You might like to try a simple two player game where one player moves one object using AWSD and another player moves a second object using JIKL.