// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 5-3: Rollovers
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
line(100,0,100,200);
line(0,100,200,100);
// Fill a black color
noStroke();
fill(0);
// Depending on the mouse location, a different rectangle is displayed.
if (mouseX < 100 && mouseY < 100) {
rect(0,0,100,100);
} else if (mouseX > 100 && mouseY < 100) {
rect(100,0,100,100);
} else if (mouseX < 100 && mouseY > 100) {
rect(0,100,100,100);
} else if (mouseX > 100 && mouseY > 100) {
rect(100,100,100,100);
}
}
After a 20 year break from programming this excercise really grabbed my interest. After doing it as above I tried nested if statements (If mouse on left side of screen then if mouse at top of screen etc.) This didn’t make it any prettier.
Then I remembered you could do this
x=(width/2)*int(mouseX>width/2);
y=(height/2)*int(mouseY > height/2);
rect(x,y,width/2,height/2);
What fun!
Comment by Kit — July 27, 2009 @ 6:07 am
I did this exercise only with ifs first i thought i made a mistake but it worked as well i am wondering what is the plus to use if else ?
Thanks
PM
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
line(100,0,100,200);
line(0,100,200,100);
// Fill a black color
noStroke();
fill(0);
// Depending on the mouse location, a different rectangle is displayed.
if (mouseX < 100 && mouseY 100 && mouseY < 100) {
rect(100,0,100,100); }
if (mouseX 100) {
rect(0,100,100,100);}
if (mouseX > 100 && mouseY > 100) {
rect(100,100,100,100);
}
}
Comment by Patrick Mimran — March 14, 2010 @ 10:16 am
In this case, it doesn’t really matter, but an if/else structure will only allow the first instance of true to be executed whereas multiple if statements are treated separately. The following illustrates the point more effectively:
int x = 50; if (x > 30) { println("A"); } else if (x > 20) { println("B"); } if (x > 30) { println("C"); } if (x > 20) { println("D"); }Comment by Daniel Shiffman — March 15, 2010 @ 10:05 am