Functions for Organizing Code
You have called functions from your code to make the computer do things. You call rect(…) to draw a rectangle, fill(…) to change the fill color. Now you are going to write your own functions. You have already seen examples of what one kind of function looks like when you start a new project:
1 2 3 4 | function setup() { createCanvas(windowWidth, windowHeight); background(255); } |
You create a function by writing “function”, then the name of the function, open and close parenthesis and open and close curly braces.
Here is another example:
1 2 3 4 5 6 7 8 9 10 11 12 | function drawShape() { push() translate(200,200); beginShape(); vertex(-100,-50); vertex(60,-50); vertex(100,0); vertex(100,50); vertex(-100,50); endShape(CLOSE); pop(); } |
We can then call our function from the draw function:
1 2 3 | function draw() { drawShape(); } |
This isn’t very useful though since the shape is always drawn to the screen at (200,200). As you know from your use of other functions, you can pass values into functions:
1 2 3 4 5 6 7 8 9 10 11 12 | function drawShape(x,y) { push() translate(x,y); beginShape(); vertex(-100,-50); vertex(60,-50); vertex(100,0); vertex(100,50); vertex(-100,50); endShape(CLOSE); pop(); } |
Complete Activity 31
As you write longer code, breaking up your code into functions like this will make your code easier to read and make it easier for you to make changes. If you wanted to draw a red creature and a blue creature before you would probably have copy pasted code and changed the fill color. If you later wanted a different creature, you would have had to change code in more than one place.
An important principle of good coding is to only do something once. If you can put the code to draw something in a single function, then it is easier to change that drawing by changing the code once vs searching for all of the places something has changed. Trust me, when you get to 500+ lines of code (which is still small by industry standards), you want to be organized.
Complete Activity 32