In your projects, you may need to define very specific parameters with your conditional statements. A program may have several animations, boundaries, and/or responsive actions running simultaneously. In order to make sure programming events are all uniquely defined, we often need to conjoin several expressions inside of one condition.
As you test the program, you will notice that whenever mouseX is past 25, the face displays. That is pretty handy but what if we want even more specificity for our rollover face? What about the face displaying whenever our mouse is within any side of the blue rectangle? To write a conditional that can specify all of these areas, we will need to use logical operators to conjoin multiple expressions.
The logical operator, “or” (expressed with double pipes: | | ) conjoins two alternate conditions. If either side of the | | operator is true then the code will be executed. The logical operator “and” (expressed with double ampersands: &&) combines conditions. All conditions conjoined by the && operator must be true before the code will be executed. The “not” operator (expressed with an exclamation point: !) is used to negate an expression. We will use this in future lessons.
In summary, logical operators combine simple relational statements into more complex expressions. It is important to note that parentheses enclose each individual condition and the entire conjoined condition for the sake of clarity.
Keep an eye out for logical errors when conjoining conditions. In this example, the condition will never be true because it is logically impossible.
xxxxxxxxxx
function setup() {
createCanvas(200, 200);
}
function draw() {
background(255);
rectMode (CENTER);
fill (9,215,232);
rect (100,100,150,150);
if (mouseX>25){
//draw face
fill (0);
ellipse (70,80,25,25);
ellipse (130,80,25,25);
fill (255);
ellipse (65,75,10,10);
ellipse (125,75,10,10);
fill (255,0,0);
rect (100,140,80,20);
}
}