Home

Conditionals

In most programs, we want to execute different actions depending on certain conditions. For example, if the user presses a particular key, or clicks the mouse, we want something to happen. Or if the user scores 1000 points, we want to show a win screen.

We do this with if conditionals, like so:

if(true)
{
  rect(0, 0, 100, 100);
}

That piece of code is essentially useless. The test for the if is just true, so it’s always comes out true. Usually, we want to check on variables:

if(x > 5)
{
  rect(0, 0, 100, 100);
}

Now the rectangle will only be drawn if the variable x is greater than 5.

You can write else after an if to handle cases when the if test comes out false:

if(x > 5)
{
  rect(0, 0, 100, 100);
}
else
{
  ellipse(0, 0, 100, 100);
}

You can put if’s inside if’s, as deep as you wish:

if(x > 5)
{
  if(x <= 10)
  {
    rect(0, 0, 100, 100);
  }
}
else // i.e., x <= 5
{
  if(x < 0)
  {
    ellipse(0, 0, 100, 100);
  }
}

In that example, the rectangle is only drawn if x has one of these values: 6, 7, 8, 9, 10. This is because the rectangle is only drawn if both top if’s are true. And the ellipse is only drawn if x has one of these values: 1, 2, 3, 4, 5. This is because the first if has to be false, so that we’re in the else, and the inside if needs to be true.

Here is a more practical use. This program restarts the rectangle at the top of the screen if it goes past the bottom (a kind of wrapping around):

int y = 0;

void setup()
{
  size(400, 400);
  rectMode(CENTER);
}

void draw()
{
  background(255);
  fill(0);
  rect(200, y, 100, 100);
  
  y = y + 1;
  
  if(y > 400)
  {
    y = 0; // reset y if it's too large
  }
}

Collision detection example

// missiles and collision detection

// character x & y
int cx = 400;
int cy = 500;

// enemy x & y
int ex = 200;
int ey = 200;

// missle x & y (starts off screen)
int mx = -10;
int my = -10;

void setup()
{
  size(800, 600);
  rectMode(CENTER);
}

void draw()
{
  background(0);
  // draw character
  fill(#0000ff);
  rect(cx, cy, 50, 50);

  // draw enemy
  fill(#ff0000);
  ellipse(ex, ey, 100, 100);
  
    // collision detection
  if(get(mx, my) == #ff0000)
  {
    println("hit");
  }
  
  // draw missile
  fill(#ffffff);
  ellipse(mx, my, 20, 20);
  
  // move missile
  my = my - 5;
  

}

void keyPressed()
{
  if(key == 'f')
  {
    mx = cx;
    my = cy;
  }
  if(key == 'a')
  {
    cx = cx - 5;
  }
  if(key == 'd')
  {
    cx = cx + 5;
  }
}

CSCI 111 material by Joshua Eckroth is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Source code for this website available at GitHub.