Week 3: Looping and Interactivity

Warmup questions

You can do this solo or with a partner.

  1. Create a simple drawing program. A circle is drawn on screen where your mouse is located. When you click the mouse, it should choose a different color fill for the circle that you are drawing with.

  2. Create a simple program where if you click on the right side, the right half of the canvas turns black. If you click the left side, the left half turns black.

  3. Consider this mousePressed function to count clicks:

let clicks = 0;
function setup(){ 
  createCanvas(100,100);
}
function draw(){
}
function mousePressed(){
  print("I am pressing the mouse.");
  clicks++; //clicks = clicks + 1
  print("I pressed the mouse "+clicks+" times.");
}

The very first time I press the mouse it says “I pressed the mouse 1 times.” That is not grammatically correct. Please change this so that the first time I click the mouse it says “I have clicked the mouse once.”

Interactive portraits review

interactivity with keyPressed

Reminder: when you are checking if two things are equivalent inside an IF block, you must use two equal signs ==.

for example:

function keyPressed(){
  //this function runs anytime you press a key
   if (keyCode === LEFT_ARROW) {
    //move left
    x--;
   } else if (keyCode === RIGHT_ARROW) {
    //move right
    x++;
  }
}

New Variables: Booleans

So far we have covered numbers such as integers (whole numbers) or floats (decimals).

A boolean is a variable that is set to true or false. This is a binary choice.

Example

let iMadeMyBedToday = true;

Built-in boolean: mouseIsPressed

Don’t confuse mousePressed() with mouseIsPressed.

mouseIsPressed is a builtin variable (like mouseX, or width) that we can use in our programs. We normally use it in our draw loop to detect if a key is building held down. If any key is being held down, then mouseIsPressed = true

example

function draw() {
  background(237, 34, 93);
  fill(0);

  if (mouseIsPressed) {
    ellipse(50, 50, 50, 50);
  } else {
    rect(25, 25, 50, 50);
  }

  print(mouseIsPressed);
}

Looping

Sometimes we want to do something many times. Over and over again.

We use loops to do this.

For loop

Use the for-loop to specify having an action occur a set number of times.

for (let i = 0; i < 65; i++){
    print("My age is "+i);
}

There are 3 sections in the for loop statement. First we initialize the temporary variable. Then we test to see if the statement is valid. Then we increment the temporary variable at the end of each loop.

Another example

for (let i = 99; i >= 0; i--){
  print(i+" bottles of beer on the wall, "+i+" bottles of beer...");
}

How would we add to this code to complete the song?

When to use an if statement or for-loop?

If you are testing whether something is true

When you are asking a question, use an if statement.

Examples: Is my ball off screen? Is the color black?

If you need to make lots of things, use a for-loop

Examples: I need 300 circles.

Events

An event is something your web browser does or something the user of your software does which indicates interaction. Examples are pressing a mouse button, dragging the cursor across the screen or pressing a key. p5.js gives a number of built-in functions to make it easier to work with events.

A full list of events can be found in the p5.js Reference section on events

function mousePressed(){
  //this code will run anytime the mouse is Pressed
  print('you clicked');
}

function keyPressed(){
  //this function runs anytime you press a key
   if (keyCode === LEFT_ARROW) {
    //move left
   } else if (keyCode === RIGHT_ARROW) {
    //move right
  }
}

Events happen independently of (outside) the draw loop.

Additional events:

mousePressed()
mouseDragged()
mouseReleased()
mouseClicked()
mouseWheel()
mouseMove()
keyPressed()
keyReleased()
keyTyped()
keyIsDown()
touchStarted()
touchMoved()
touchEnded()

Bouncing

Q: How do we keep the ball on screen by bouncing along the edge?
A: We check the ball’s x position to see when it is greater than the right side of our canvas (x > width) or less than the left side of our canvas (x < 0).

We can change the ball’s position by changing its xspeed (which is the amount we add to x each time draw runs).

let x = 200;
let xspeed = 1;
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(0);
  
  circle(x,y,10);
  x = x + xspeed;
  
  if (x > width){
      //make it bounce
    xspeed = -1;
      }
  if (x < 0){
    xspeed = 1;
  }
}

Rollovers (buttons)

For our bouncing ball, we needed to detect when we were on the page or not. This same technique can be used to detect when a user has clicked on a button.

First we see if our mouse has rolled over the rectangle

function setup() {
  createCanvas(400, 400);

  rectMode(CORNER);
}

function draw() {
  background(220);

  rect(150,150,100,100);

  if (mouseX >= 150 && mouseX <= 150+100 && mouseY >= 150 && mouseY <= 150+100) {
  //if we've rolled over do something
    fill(0);
   } else {
		fill(255);
   }

}

How do we take this code and alter it so that the button changes color only when we press the mouse?

Answer: place the code inside a test for whether the mouseIsPressed

Read

Chapters 6 and 7 in the book Getting Started with p5.js

Watch

The Coding Train videos

How to rotate shapes - translate, rotate, push, pop

How to use scale

Uploading media files

Bouncing Balls of Color

Take our bouncing ball starter code from here.

Duplicate the code sketch. Now add:

  • when the ball bounces, change the color
  • when the ball bounces, change the size of the ball
  • when the ball bounces, change the speed of the ball

Hints: Think about what new variables you need. You’ll need variables for the r, g and b color, for the width and height of the ball (could be the same), and the speed.

Turn in: post link to your code on Brightspace

BONUS: Optional challenge:

  • Change the sketch so that you see the trail of the bouncing ball. Add a pinball bumper (circular) somewhere in the canvas so that if the ball hits it, it resets the canvas blank.