Variables

Let’s have more fun with variables:

int myDiameter = 10;
 
void setup() 
{
  size(500, 500); 
  smooth();
  noStroke();  
}
 
void draw() 
{ 
  background( 0, 0, 0);
  ellipse(250, 250, myDiameter, myDiameter);
}

I use a var for the radius so I don’t have to type the number every time i want to adjust it.

Since it’s a variable it can be changed:

myDiameter = myDiameter+1;

or

myDiameter++;

What if I want the resizing to be slower?

myDiameter = myDiameter+.5;

Error! It has to be declared as float.

Framerate
By the way there’s another way to slow down the *entire* sketch by changing the framerate.

frameRate(10);

Integer vs. Float
Here’s a nice example from processing.org

int a = 0;      // Create a variable "a" of the datatype "int"
float b = 0.0;  // Create a variable "b" of the datatype "float"
 
void setup() {
  size(640, 360);
  stroke(255);
  frameRate(30);
}
 
void draw() {
  background(0);
 
  a = a + 1;
  b = b + 0.2; 
  line(a, 0, a, height/2);
  line(b, height/2, b, height);
 
  if(a > width) {
    a = 0;
  }
  if(b > width) {
    b = 0;
  }
}

It’s good practice to have variables instead of numbers for a number of reasons…

What about the other parameters of the ellipse?
Try to use variables there too!
Give them meaningful names.

Now use that variable to make the circle move from the left to the right!

wrap around the screen! (if)
go back and forth!

Mouse trailer

Some “temporary” variables can be declared inside functions and blocks. Note: these variables won’t be “visible” outside that block (scoping).

void draw() 
{ 
  background( 0, 0, 0);
 
  float dx = mouseX - posX;
  float dy = mouseY - posY;
 
  posX += dx/10;
  posY += dy/10;
 
  ellipse(posX, posY, myDiameter, myDiameter);
}

Let’s analyze this.

How can we make the circle faster?

How can you make the circle follow the mouse pointer only when the mouse button is down?

Digression: something fun with the background

 
//background( 0, 0, 0);
fill(0,0,0);
rect(0,0, width, height);
fill(255, 255, 255); //back to white

Fill as opposed to background can accept an alpha value. Try 10. Why is that?

Posted in

Post a comment