Keyboard Input

Adding More Controls

Processing is not restricted to mouse movement for input and output. In this activity, you will extend your figure from Animate Your Figure to incorporate keyboard button presses as well. In order to do so, you will use a variety of pre-built variables for keyboard input similar to the mousePressed variable.

As usual, you should read and reference the Processing Documentation in order to understand the use of these constructs. However, here is a brief outline of how the keyboard input system in Processing works.

Keyboard Input

If a key is pressed, the built-in variable keyPressed is set to TRUE. This means that a simple test, such as if (keyPressed), will allow the execution of a block of code if (and only if) a key has been pressed. Another variable, named key, can be used to check the contents of the key that has been pressed. In other words, if (key == ’A’) will check the pressed key against the capital letter A. The key variable may indicate a key has been pressed that is not an ASCII encoded character. In this case, if (key == CODED) will evaluate to TRUE. Should this occur, the value of the key is stored in the variable keyCode. For example, the following code checks to see if a key has been pressed, then if it is a non-ASCII encoded key, and finally if it is the “up arrow” key:

if (keyPressed)
{
     if (key == CODED)
     {
          if (keyCode == UP)
          {
                // up arrow key stuff happens
          }
          else
          {
               // other stuff happens
          }
     }
}

Instructions

Modify your sketchbook from Animate Your Figure as follows:

  1. Add the ability to respond to key press commands.
  2. Include the use of at least five key strokes, including a mix of alphanumeric characters and the arrow keys.

Much like the mouse button press, each of these key presses should alter the appearance or behavior of the figure in some unique way. Remember to reference the Processing Documentation for examples.

Submission

Submit the .pde of your Processing sketchbook.

Reference Starting Points

Variables Control Structures
keyPressed if
key else
keyCode while