Functions

This draws a house:

void setup()
{
  size(500, 500);
  background(255);
  smooth();
  noLoop();
}
 
void draw()
{
  triangle(15, 0, 0, 15, 30, 15);
  rect(0, 15, 30, 30);
  rect(12, 30, 10, 15);
}

We can put the instructions in a function that can be reused multiple times and makes the code more readable:

 
void setup()
{
  size(500, 500);
  background(255);
  smooth();
  noLoop();
}
 
void draw()
{
  house();
}
 
void house()
{
  triangle(15, 0, 0, 15, 30, 15);
  rect(0, 15, 30, 30);
  rect(12, 30, 10, 15);
}

We can add parameters (aka arguments) to generalize the house drawing function making our code more flexible:

void setup()
{
size(500, 500);
background(255);
smooth();
 
noLoop();
}
 
 
void draw()
{
house(200, 200, 255, 0, 0);
}
 
void house(int x, int y, int r, int g, int b)
{
  triangle(x + 15, y, x, y + 15, x + 30, y + 15);
  rect(x, y + 15, 30, 30);
  rect(x + 12, y + 30, 10, 15);
}

Now add 3 more parameters to make the fill color customizable.

Returning values
Functions are more useful when they return values.
Void is used when a function doesn’t return anything.

float distance(float x1, float y1, float x2, float y2) {
  float dx = x1 - x2;
  float dy = y1 - y2;
  float d = sqrt(sq(dx) + sq(dy));
  return d;
}
Posted in

Post a comment