Responding to Keyboard Input

Try the following code:

int width = 500;
int height = 500;
int x;
int y;
int size = 20;

void setup() {
   size(500, 500);
   background(236, 0 , 128);
   x = width/2;
   y = height/2;
   stroke(255, 126, 0);
   fill(238);
   rect(x, y, size, size);
}

void draw() {

}

void keyPressed() {
   if (key == CODED) {
     if (keyCode == UP) {
       y = y - size;
     }
     else if (keyCode == DOWN) {
       y = y + size;
     }
     else if (keyCode == RIGHT) {
        x = x + size;
     }
     else if (keyCode == LEFT) {
        x = x - size;
     }

     background(236, 0 , 128);
     stroke(255, 126, 0);
     fill(238);
     rect(x, y, size, size);
   }
}

So, what are we doing here? In order to respond to keyboard input we have to have a method keyPressed().

if (key == CODED) determines whether it’s a special key – up, down, left, right, shift, alt and control. We update our x and y variables, declared at the top, accordingly and redraw our square. Thus, our square moves about in response to what we’re doing on the keyboard. (Full detail).

Each time, we call background() again, what happens if you remove that line?

Responding to keyboard input

Responding to keyboard input

There’s a potential problem here though, can you spot it? If we go too far left, right, up or down our square can leave the screen. Can you fix that?

One Response to Responding to Keyboard Input

  1. Pingback: Processing » Archive » Pacman

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>