Unit 2 Response & Draw
How can control flow allow for user interactions?

2.2 Rectangles and Clicks

How can I use mouse clicks in p5.js?


Overview

This learning activity introduces if statements and boolean expressions, both simple and compound. They are applied to locating the mouse on the screen, and creating rectangular and circular buttons that the user can hover and click on.

Suggested Duration

45 - 90 minutes

Objectives

Students will be able to:

  • Use conditionals to define a reactive rectangular button.
  • Use mouseIsPressed to create mouse click reactions.

Vocabulary

mouseIsPressed A built-in variable that is True when the mouse button is pressed, and False when it is not pressed.
Efficiency In this case, making it easier and faster to debug and edit your code.
Nesting Conditionals When one conditional lives within another -- meaning then that both of the conditions have to be met before your code will execute.
User Experience A person’s internal experience as they interact with an existing product or service. (note: this is different from user experience design)

Resources

Is it Over a Rectangle?

Determining whether the mouse is over a rectangle requires a more complex boolean expression (see lines 13 and 14):

What you see in lines 13 and 14 is a compound boolean expression. (mouseX > x), (mouseX < x+w), (mouseY > y) and (mouseY < y+h) are individual boolean expressions: they evaluate to either true or false.

Here they are joined together by the logical operator AND (&&). AND evaluates to true only the expressions on its left and right are both true. Boolean expressions can also be combined using the OR (||) and NOT (!) logical operators. For more in-depth explanations please see Daniel Shiffman's video tutorials here and here.

Click

When a user clicks the mouse, the mouseIsPressed variable is set to True. We write a conditional using this boolean variable to make something happen when the mouse is clicked. Any code we write within this conditional will be executed whenever a click event happens. This kind of conditional is known as an event handler: they allow us to respond to events when they happen.

Let's add a mouseIsPressed conditional to this mouse-following program so that the color of the circle changes to a random color whenever we click:

Click on a Rectangle

Combining the code from the previous two sketches we can create a button: in the following example we check whether the mouse is over the rectangle before we re-set our R, G, B variables in our mouseIsPressed conditional.

A Circular Button

In this last example we make three changes:
    1. Draw a continous line by using pmouseX and pmouseY
    2. Make our button circular and use the dist function to check whether the mouse is over it (if the distance between the mouse and the center of the circle is smaller than its radius, then it is), and
    3. Add hovering functionality to our button by making its fill black if the mouse is over it.