Overview
This learning activity builds on conditional statements using the Logical Operators && and ||. Students create a hover button by changing the fill of a rectangle while hovering over it with the mouse.
Overview
This learning activity builds on conditional statements using the Logical Operators && and ||. Students create a hover button by changing the fill of a rectangle while hovering over it with the mouse.
Suggested Duration
45 - 90 minutes
Objectives
Students will be able to:
Vocabulary
Conditional Statements | A set of rules performed if a certain condition is met. |
---|---|
Boolean Expression | A logical statement that is either TRUE or FALSE. |
|| OR | Joins two statements such that if one is true, the whole statement is true. |
&& AND | Joins two statements to make sure they are both true. If one is false, the whole statement is false. They must both be true for the whole statement is false. |
Expression | A group of terms (the terms are separated by + or - signs) |
Relational operators | <, >, >=, <=, &&, || |
Resources
&& And
&& is used whenever you want the bracketed code to be executed only if both conditions evaluate to true.
|| Or
When we would like that code to be executed as long as one of the conditions evaluate to true, we use the logical operator "or." They syntax for "or" in p5 is two pipes (||). If we applied this to our last example, it wouldn't be very helpful. Every number is either greater than 200 or less than 400.
Instead, let's edit that code and pick two separate ranges. If the mouse is hovering within either of them, we'll draw an ellipse.
Exercise 1: Make a Rollover Button
Now that you know how to change a value when the mouse is in a specific range, we can start thinking about buttons. Try to change a fill of a rectangle when the mouse is hovering over it. You will need to think the range of both the mouseX and the mouseY positions.
You'll need to think about the the locations of the beginning and end of the shape on the x and y axis. The mouseX position needs to be greater than the left side of the rect, and less than the right side of the rect, and greater than the top line of the rect, and less than the bottom line of the rect. The boolean will be long but it's just a repetition of the same concept.
The square is located in the center of the canvas and the width is 40 pixels. The first line of the rect is therefore 20 pixels less than the center of the canvas (width/2-20.) The second line is 20 pixels greater than the center of the canvas (width/2+20). Your boolean will therefore read (mouseX>width/2-20) && (mouseX
If you're feeling ambitious, make 2 rollover buttons!