← All lessons/Conditionals· Lesson 13 of 32

Branching on a value

Use a value like mouseX to decide what your sketch draws — the heart of interaction.

About 8 min

Conditions that change

Conditions get powerful when the value they test changes. Inside draw(), the special variable mouseX always holds the mouse's horizontal position — from 0 on the left edge to 400 on the right. Test it with an if and your sketch reacts to where the cursor is.

Move your mouse across the canvas — the left half turns red, the right half blue.

Each frame, p5 checks mouseX < 200. On the left half it's true (red); on the right half it's false (blue). The same idea works with any value — a score, a frameCount, a variable you change over time.

The pattern

Read a changing value, compare it in an if, and draw differently in each branch. That's the recipe behind buttons, games, and animations.

Your turn

Define a draw function. Inside it, check mouseX: if mouseX < 200, call background(220, 60, 60); otherwise call background(60, 60, 220). (You're building the pattern — it doesn't need to match a specific mouse position to pass.)

NOTE

We grade the structure here — that you branch on mouseX with an if / else — not a particular color, because the mouse position varies as you move.

Hints