FRI | Conditional Statements

Week 02 | Conditional Statements Continued #


Inspiration #

John Whitney

Incrementation operators #

Logical operators && and || #

Example #03 | Bouncing Ball #

Click to see the code
let x;
let y;
let s = 100;
let xSpeed;
let ySpeed;

function setup() {
  createCanvas(500, 450);
  background(130, 80, 130);
  x = random(100, width - 100);
  y = random(100, height - 100);
  xSpeed = random(1, 5);
  ySpeed = random(1, 5);
}

function draw() {
  
  // draw background with some transparency
  background(130, 80, 130);
  
  // update values
  x = x + xSpeed;
  y = y + ySpeed;
  
  // check if the circle hit the wall
  if (x >= width - s / 2 || x <= 0 + s / 2) {
    xSpeed = -xSpeed;
  }
  if (y >= height - s / 2 || y <= 0 + s / 2) {
    ySpeed = -ySpeed;
  }

  // draw
  noStroke();
  fill(255);
  circle(x, y, s);
}

switch #

The switch statement is used to perform different actions based on different conditions. It’s really useful in situations where the input value has three or more possible options (like the keys from a keyboard).

switch(expression) {
  case a:
    // code block
    break;
  case b:
    // code block
    break;
  default:
    // code block
} 

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

Example #

This example checks what key is pressed and does different things based on the input.

  • Keys 1 to 5 change the color
  • Keys u and d change the size of the brush
  • Pressing space will clear the drawing
Using mouseIsPressed and keyIsPressed inside the draw() means that the program looks if they are pressed every frame. This might sometimes have unintended consequences. A better way would be to use the mousePressed() and keyPressed() functions. We will go through them in later classes but feel free to explore them already.

Resources #


Homework #

Add your version of the bouncing ball sketch to our Open Processing class. It can just be pretty much the same we did in class, but maybe try adding some of your own flavor to it.

For extra challenge, try the following:

  • something happens when the ball hits the wall (color changes)
  • try adding gravity and friction
  • try replacing the 2d shape with an image