p5.js mouse, keyboard and if’s
In this variation of an earlier program, the ellipses are red if the mouse is pressed and green otherwise
mouseIsPressed p5.js has a Boolean variable mouseIsPressed Variable means it can change Boolean means it is true or false The structure of if is If(ask some true-false question){ what to do if the answer is true } else { what to do if the answer is false }
mouseX and mouseY mouseX and mouseY are built-in variables in p5.js that indicate The horizontal position of the mouse from the left edge of the canvas: mouseX The vertical position of the mouse from the top of the canvas: mouseY Since there is no background() in the function draw, we “remember” what was drawn earlier and draw on top of it
Nested if’s: within the block of code associated with an if (inside curly brackets), we can ask further (follow-up) questions
Nesting cont. You only execute line 11 if the mouseIsPressed is true and if it is true that the mouseX is less than half the width You only execute line 13 if the mouseIsPressed is true and if it is false that
else if: A different type of follow-up question
Else if Cont. The else-if structure allows one to ask a follow-up question in case the first question produced an answer of false First we ask if the horizontal position is less than 100, when that turns out to be false we ask the follow-up question is it less than 200, when that is false we ask the follow question is it less than 300, etc.
Boolean AND: Asking if two things are true without nesting
ANDED if(200<mouseX && mouseX<400){ fill(255,0,0); } There are two conditions (true-false) questions: 1) is the horizontal position greater than 200; 2) is the horizontal position less than 400 AND (uses &&) mean BOTH must be true for the combination to be true Result horizontal position must be between 200 and 400
Another AND example: the conditions can be on different variables (e.g. horizontal and vertical positions)
Boolean OR: Asking if either of two things is true (uses || between conditions)
Another OR example: either less than 200 or more than 400
Combining AND’s with OR’s
Taking Precedence When combining Boolean AND’s and OR’s, remember that an AND is a bit like multiplication and an OR is a bit like addition. Thus like multiplication and addition, there is a precedence (order of operations). Like multiplication is done before addition, ANDing is done before ORing. Parentheses can force a higher precedence
Without parentheses
With parentheses
Japanese Flag
The function keyPressed handles the “typing” event The function keyPressed handles the “typing” event. If the code (ASCII) for the character typed is an up arrow, change y the vertical position The print statement shows results in the console
UP_ARROW same as 38
The Numpad uparrow has a code of 104, so an OR allows the user to press either up arrow
Else if to allow down arrows
More code to allow horizontal moves