Detecting Transitions

Detecting Transitions

This tutorial shows how to detect when the mouse enters a rectangle — a state transition rather than a state. It progresses from simple boolean tracking to classes and arrays, building up to detecting transitions across an arbitrary number of buttons.

Use the ◀ ▶ buttons or arrow keys to step through the stages. Move the mouse over the canvas to interact. Drag any number in the code to adjust it live.

We want to tell when the mouse enters a rectangle. This involves looking for a transition. We want to detect when it goes from not being inside the rectangle, to being inside the rectangle.

Here’s the setup. Draw a green rectangle. This is the button. We’re going to detect whether the mouse is inside of it.

Draw crosshairs around the mouse position. This isn’t strictly necessary (the user can just look at the mouse cursor), but I find it helpful to have something on the canvas that reflects the variables that I’m working with, just to check that the basic “plumbing” is working.

let buttonX = 100;
let buttonY = 100;
let buttonWidth = 200;
let buttonHeight = 50;

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(100);

  // draw a big button
  noStroke();
  fill("lightgreen");
  rect(buttonX, buttonY, buttonWidth, buttonHeight);

  // draw crosshairs to highlight the mouse position
  noFill();
  stroke("blue");
  strokeWeight(4);
  line(mouseX - 10, mouseY, mouseX + 10, mouseY);
  line(mouseX, mouseY - 10, mouseX, mouseY + 10);
}
Step 1 of 19

Try it on OpenProcessing: Detecting Transitions