Week 05: Functions

Topics:

  • Defining and calling functions

  • Function terms: parameters, arguments, return type, return statement, inputs, outputs, side-effects

  • keywords: void, return

  • Ideas: "blackbox", "DRY: Don’t-Repeat-Yourself"

  • Function stack

  • Spinning animations

1. Resources:

2. Flower Function

/*
 * Aline Normoyle
 * 10/7/2020
 * Draw flowers randomly on the canvas
 */
void drawFlower(float cx, float cy, float radius) {
  int numSlices = 100;
  float delta = 2 * PI / numSlices;
  float k = 4;
  int numRepetitions = 5;
  beginShape();
  for (int i = 0; i < numSlices * numRepetitions; i++) {
    float angle = i * delta;
    float x = cx + radius * cos(k * angle) * cos(angle);
    float y = cy + radius * cos(k * angle) * sin(angle);
    vertex(x, y);
  }
  endShape(CLOSE);
}
void setup() {
  size(1000, 1000);
  background(0);
  blendMode(ADD);
  for (int i = 0; i < 500; i++) {
    float radius = random(10, 100);
    float cx = random(0, width); // center X
    float cy = random(0, height); // center Y
    color c = lerpColor(#E9FA08, #3308FA, cx/width);
    fill(c, 50);
    drawFlower(cx, cy, radius);
  }
}

3. Spin

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

void draw() {
  background(255);
  fill(200);

  // Play with the pivot point to change how the rectangle spins
  float pivotPtX = 250;
  float pivotPtY = 250;

  float angle = millis()/1000.0;
  push();
  translate(pivotPtX, pivotPtY);
  rotate(angle);
  scale((sin(angle)+1.0)*0.5);
  translate(-pivotPtX, -pivotPtY);
  rect(250,250,300,300);
  pop();
}