if 文をもう少しだけ掘り下げます。
void setup()
{
size(800, 600);
}
void draw()
{
background(240, 240, 240);
if (mouseY < height / 2) {
fill(126, 190, 171);
noStroke();
circle(width / 2, height / 2, 150);
}
if (mouseY >= height / 2) {
fill(238, 187, 203);
noStroke();
rect(300, 250, 200, 100);
}
}
void setup()
{
size(800, 600);
}
void draw()
{
background(240, 240, 240);
if (mouseY < height / 2) {
fill(126, 190, 171);
noStroke();
circle(width / 2, height / 2, 150);
} else {
fill(238, 187, 203);
noStroke();
rect(300, 250, 200, 100);
}
}
この2つのプログラム、全く同じ動作をします。
else というものが出てきました。
else は、if と組み合わせて使います。使い方は以下です。
if (条件) {
条件が成立する場合、ここに記述されたプログラムが実行される
} else {
条件が成立しない場合、ここに記述されたプログラムが実行される
}
else を使うことで、最初の例の if(mouseY < height / 2) と if(mouseY >= height / 2) のように、条件を重複的に書く必要がなくなるので便利です。
void setup()
{
size(800, 600);
}
void draw()
{
background(255);
if (mouseX > width / 2) {
fill(200, 0, 0);
} else {
fill(0, 0, 200);
}
noStroke();
circle(400, 300, 200);
}
関数 draw() 内の処理を図で表すと、
こんな感じです。

void setup()
{
size(800, 600);
}
void draw()
{
if(mouseX > width * 2 / 3) {
background(100, 100, 100);
} else if (mouseX > width / 3) {
background(150, 150, 150);
} else {
background(200, 200, 200);
}
}
else if を使うと複数の条件分岐を表現できます。
if (条件1) {
条件1が成立する場合、ここに記述されたプログラムが実行される
} else if (条件2) {
条件1が成立しない、かつ、条件2が成立する場合、ここに記述されたプログラムが実行される
} else {
条件1が成立しない、かつ、条件2も成立しない場合、ここに記述されたプログラムが実行される
}
void setup()
{
size(800, 600);
}
void draw()
{
background(255);
if (mouseX > width * 2 / 3) {
fill(200, 0, 0);
} else if (mouseX > width / 3) {
fill(200, 200, 0);
} else {
fill(0, 0, 200);
}
noStroke();
circle(400, 300, 200);
}
関数 draw() 内の処理を図で表すと、
こんな感じです。

float s;
void setup()
{
size(400, 300);
}
void draw()
{
background(240, 240, 240);
if (mouseX > width * 3 / 4) {
fill(255, 67, 89);
s = 60;
} else if(mouseX > width * 1 / 2) {
fill(255, 138, 37);
s = 90;
} else if (mouseX > width * 1 / 4) {
fill(255, 215, 95);
s = 120;
} else {
fill(0, 120, 255);
s = 150;
}
noStroke();
circle(width/2, height/2, s);
}
int score = 0;
void setup()
{
size(800, 600);
}
void draw()
{
score = 100 * (height - mouseY) / height;
String s;
if (score >= 90) {
s = "S";
} else if (score >= 80) {
s = "A";
} else if (score >= 70) {
s = "B";
} else if (score >= 60) {
s = "C";
} else {
s = "D";
}
background(255 * (height - mouseY) / height);
fill(0);
textSize(52);
text(score, 300, mouseY);
text(s, 400, mouseY);
}