Learning Processing #2 – Functions and Arrays

This week’s workshop covered using functions and arrays in processing.

color[] p ={ #eb5050, #E67012, #FCAC22, #AA5903 };
void setup(){
  size(800,400);
  background(0);
}

int r=0;

void draw(){
  fill(0,3);
  rect(0,0,width,height);
  translate(width/2,height/2);
  rotate(r);
  stroke(255);
  noFill();
  for(int i=0; i<width; i=i+35){
    house(mouseX,20,p[int(random(p.length))]);
  };
  r=r+1;
}

void house(int x, int y, color c){
  fill(c);
  stroke(255);
  triangle(x+15,y,x,y+15,x+30,y+15);
  rect(x,y+15,30,30);
  rect(x+12,y+30,10,15);
}

The above code contains an array of colors called “p” at the top, which is referenced later at line 17 to draw a random color from the array. A function called “house” is then defined at the end of the sketch, which draws a small 2d house made up of rectangles and a triangle at set coordinates. The use of a for loop on line 16 repeats this function, and combined with rotate(r) and r=r+1, creates a circle of these houses looping around the center of the screen based on the coordinates provided as more houses are drawn in each frame which rotate around by 1 each frame.

The width of the circle of houses is determined by the mouse's horizontal position.
The width of the circle of houses is determined by the mouse’s horizontal position.

Functions and arrays are ways to repeat code without having to rewrite it each time – an array of colors to be used can be referenced multiple times in one sketch, and a function can be called several times as well. These are ways to cut down on file sizes and make code cleaner and easier to read.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s