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

2.1 Hover and Conditional Statements

How can I use conditionals to create hover reactions?


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 circular buttons that the user can hover on for a reaction.

Suggested Duration

45 - 90 minutes

Objectives

Students will be able to:

  • Use the dist() function to calculate the distance between a circle center and the mouse
  • Use conditionals to create hover reactions.

Vocabulary

dist() Calculates the distance between two points.
Hover When the mouse cursor is moved over an object.
Hover Reaction Something the object does in response to the cursor being moved over it.
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 the mouse on the left or the right side of the screen?

This example does the following:

if the mouse is on the right side of the screen,
    make the fill gray
otherwise
    make the fill black

We achieve this behavior using an if statement ––see how the code starting on line 18 ressembles our pseudocode above:

Is the Mouse Over a Circle?

To determine whether the mouse is over a circle, we calculate the distance between its position and the center of the circle using p5's dist function. If the distance is less than the radius of the circle, it means that the mouse is over it.