Mouse and keyboard interaction in Processing

Lesson 3 of 14 · Processing

So far our sketches have only drawn and moved shapes. A program becomes interesting when it reacts to the user: to the mouse moving and clicking, and to keys being pressed. In this lesson you will meet the variables and functions for the mouse and keyboard and make a small game.

Before you start: what you need to know first – Processing basics (the setup() and draw() functions, drawing shapes).
How to learn: type each example into Processing (Java mode) and run it with the ▶ button. Try to solve the tasks at the end on your own first.

The mouse position: mouseX and mouseY

Processing always knows where the cursor is. The variables mouseX and mouseY hold the mouse coordinates inside the window, and pmouseX and pmouseY the position in the previous frame. Since draw() runs about 60 times a second, it is enough to draw a shape at the mouse position and it will follow the mouse.

void setup() {
  size(400, 400);
}

void draw() {
  background(230);
  fill(0, 120, 255);
  noStroke();
  ellipse(mouseX, mouseY, 40, 40);   // the circle follows the cursor
}
Why background() at the start of draw()? Without it all the previous circles would stay, leaving a trail. Try moving it into setup() and look at the difference.

Mouse clicks: mousePressed and mouseButton

There are two ways to react to a mouse button:

  • the variable mousePressed is true as long as the button is held down – useful for drawing while the button is held;
  • the function void mousePressed() is called once for each press – useful for counting clicks.

The variable mouseButton tells you which button was pressed: LEFT, RIGHT or CENTER. The example below is a simple drawing program: the left button draws, the right button erases, and the c key clears the whole drawing.

void setup() {
  size(500, 400);
  background(255);
}

void draw() {
  if (mousePressed) {                 // a mouse button is pressed
    if (mouseButton == LEFT) {
      stroke(0);                      // left button – black pen
      strokeWeight(4);
    } else {
      stroke(255);                    // right button – eraser
      strokeWeight(20);
    }
    line(pmouseX, pmouseY, mouseX, mouseY);   // a line from the previous to the current position
  }
}

void keyPressed() {
  if (key == 'c') {
    background(255);                  // the c key clears the drawing
  }
}

The line from (pmouseX, pmouseY) to (mouseX, mouseY) joins two positions in a row, so the drawing has no gaps even when the mouse moves fast.

The keyboard: key, keyCode and keyPressed

The same rule applies to the keyboard: the variable keyPressed is true while a key is held down, and the function void keyPressed() is called once when a key is pressed. The character pressed is in the variable key (e.g. 'a', ' ').

The arrows and other special keys have no character. Then key == CODED, and the key is recognised by keyCode: LEFT, RIGHT, UP, DOWN.

float x = 200;
float y = 200;
float step = 5;

void setup() {
  size(400, 400);
}

void draw() {
  background(30);
  fill(255, 200, 0);
  rect(x - 20, y - 20, 40, 40);

  if (keyPressed && key == CODED) {   // special keys (arrows) have key == CODED
    if (keyCode == LEFT)  x -= step;
    if (keyCode == RIGHT) x += step;
    if (keyCode == UP)    y -= step;
    if (keyCode == DOWN)  y += step;
  }
  x = constrain(x, 20, width - 20);   // the square does not leave the window
  y = constrain(y, 20, height - 20);
}

The function constrain(value, min, max) returns the value limited to the given range, so the square stays in the window. Because the check is done in draw(), the square moves evenly as long as you hold an arrow key.

Example: the "Hit the target" game

Let us put it all together in a small game. A red circle appears in a random place. A click inside the circle earns a point and the circle gets smaller, and a click next to the circle is a miss. We check whether the click is inside the circle using distance: if the distance from the mouse to the centre is less than the radius, it is a hit.

float cx, cy;          // centre of the target
float r = 30;          // radius of the target
int points = 0;
int misses = 0;

void setup() {
  size(500, 400);
  newTarget();
}

void draw() {
  background(240);
  fill(220, 40, 60);
  noStroke();
  ellipse(cx, cy, 2 * r, 2 * r);

  fill(0);
  textSize(18);
  text("Points: " + points + "   Misses: " + misses, 10, 25);
}

void mousePressed() {
  // the click is inside the circle if the distance from the centre is less than the radius
  if (dist(mouseX, mouseY, cx, cy) < r) {
    points++;
    r = max(10, r - 2);   // the target gets smaller and smaller
  } else {
    misses++;
  }
  newTarget();
}

void newTarget() {
  cx = random(r, width - r);
  cy = random(40 + r, height - r);
}

The function dist(x1, y1, x2, y2) calculates the distance between two points using Pythagoras' theorem. random(a, b) gives a random number from the interval, so the new target always fits completely in the window and does not cover the score text.

An idea for an upgrade: add a 30-second timer (millis() returns the number of milliseconds since the start) and print the final result at the end.

Practice tasks

Each task has a hint and a solution. The solutions have been checked by compiling them.

TASK 01Difficulty: easy

Background colour from the keyboard

Write a sketch in which the r key increases the red component of the background colour by 20, g the green one and b the blue one. When a component goes over 255, it goes back to the start. The space bar brings back a white background. Print the current values in the corner of the window.

TASK 02Difficulty: easy

A click counter

Show a number in the middle of the window. A left click increases it by 1 and a right click decreases it by 1, but the number is never less than zero.

Common mistakes and tips
  • The variable mousePressed and the function mousePressed() are not the same: the variable is true while the button is held, the function is called once per click.
  • For the arrows, first check key == CODED, and only then keyCode.
  • key tells lower-case and upper-case letters apart: 'a' is not the same as 'A'.
  • Without background() at the start of draw(), traces of the previous frames stay on the screen.

Check your knowledge

Open the quiz

Quiz: interaction

1. What do the variables mouseX and mouseY contain?




2. When is the function void mousePressed() called?




3. How do you recognise that the up arrow was pressed?




4. How do you check that a click is inside a circle with centre (cx, cy) and radius r?