Variables and Booleans#
We were using these already (mousePressed
, for example), but for completeness' sake: You can store binary true
✅/false
❌ in a variable too! This type is called a boolean
, and you declare and initialize it in much the same way you did with all the other types of variables.
!!! tip "Conventions Around Booleans
When it comes to conventions, it can be a good idea to make it very obvious from the name that this is a boolean value. In the example above, this is implied by the is
in the variable name. Using adjectives fits boolean variables very nicely, like in mousePressed
or opponentReady
. You could also have a variable in your game that toggles the main menu, you could call it menuOpen
or isMenuVisible
. You could store something about your player's state in hasRadiationPoisoning
.
A boolean can store any true
✅ or false
❌ value it gets. And just like any int
can store the result of a calculation, any boolean
can store the result of a comparison or a logic operation Just like with other variables, we can also use them to make our code more readable. Let's take our bounding box example from earlier:
This following code is longer, but may be clearer to understand:
boolean isWithinHorizontalBoundaries = mouseX > 100 && mouseX < 400;
boolean isWithinVerticalBoundaries = mouseY > 70 && mouseY < 150;
if (isWithinHorizontalBoundaries && isWithinVerticalBoundaries) {
// do some stuff
}
Relevant excerpt from Learning Processing#
(the section starts at 2:40:38 and runs through 2:50:01, the video should start and stop on these automatically.)