Meeting 14: Week 7, Long day (Thursday March 19 2:40 – 5:20)

Note that there was an intentional error in Tuesday’s last exercise. Can you find it?

This is a good time to introduce the switch statement:

void setup() 
{ 
  size(500, 500);
} 

void draw() 
{ 
  if (keyPressed) {
    switch (key) {
    case'a':
      ellipse(width/2, height/2, 100, 150);
      break;
    case 'b':
      rect(width/2, height/2, 100, 150);
      break;
    case 'c':
      arc(30+width/2, 30+height/2, 100, 100, 0, PI);     
      break;
    }
  }
}

Motion

Let’s use make a ball bounce on the floor. First, make a circle move:

void setup() 
{ 
  size(500, 500);
  x = width/2;
} 

float speed = 5;
float x;
float y = 0;

void draw() {
  background(150);

  ellipse(x, y, 20, 20);

  y+=speed;
}

Now, make it change directions when it hits the floor:

void setup() 
{ 
  size(500, 500);
  x = width/2;
} 

float speed = 5;
float x;
float y = 0;

void draw() {
  background(150);

  ellipse(x, y, 20, 20);

  y+=speed;

  if (y>=height) {
    speed = -speed;
  }
}

Now, do two thing: 1) use gravity to increase its speed as it falls and 2) reduce its speed on each bounce:

void setup() 
{ 
  size(500, 500);
} 

float gravity = .1;
float speed = 0;
float x = 320;
float y = 0;

void draw() {
  background(150);
  ellipse(x, y, 20, 20);

  y+=speed;

  speed+=gravity;

  if (y>=height) {
    speed = 0.95 * speed; // this slows the acceleration
    speed = -speed; // this reverses
  }
}

Why functions?

  • Reuse
  • Organizing

Transformations

  • Transforms move the canvas so you can draw in different places with the same code
  • Available 2D transforms are translate(), rotate(), and scale() (Why the parenthesis?)
  • pushMatrix() and popMatrix() allow you to remember where the canvas was, and then return to it’s last position

Draw a house at a given location, no transform:

void house(int x, int y)
{
  triangle(x + 15, y, x, y + 15, x + 30, y + 15);
  rect(x, y + 15, 30, 30);
  rect(x + 12, y + 30, 10, 15);
}

Same result, but using a transform:

void house(int x, int y)
{
  pushMatrix();
  translate(x, y);
  triangle(15, 0, 0, 15, 30, 15);
  rect(0, 15, 30, 30);
  rect(12, 30, 10, 15);
  popMatrix();
}
  • Rotation and scaling from this tutorial

Homework due Tuesday March 31