Interaction Design WikiProgramming

Writing our own Functions (en)

deutsche Version

Syntax of functions

There are two parts of a function. First there is the the function declaration, where the name of the function along with its properties and behaviors are defined. Next there is the function call, where the function is then actually executed. Functions may be called multiple times.

Functions can also accept input values (called parameters) that are sent to the function when called. These input parameters can change the behaviour of the function.

Functions can also return a value. This means when we return to the line where the function was called, it has now carried a number with it. In processing, functions that have no return value are declared with “void” return type.

Function Declaration

This is how the function is named, its return type and parameters defined with sudo code.


datatype functionName (parameter,.....)

{

<function contents>

<possible return value>

}


Function call 

This is how we execute a function:

functionName(parameter,.....) ;


Function Examples

This example shows how to write functions with return values.

void setup()
{
  println(addition(1,2));
  println(addition(2,10));
}
 
int addition(int parameter1, int parameter2)
{
  return parameter1 + parameter2;
}


This example shows how to use functions for creating legible and simple blocks (modularization).

void setup()
{
  size(300,300);
  smooth();
  stroke(255,255,255);
  noFill();
}
 
void draw()
{
  background(0);
 
  bommel(100,10,140,50);
  bommel(150,10,190,50);
  bommel(200,10,240,50);
}
 
void bommel(int x,int y,int length,int size)
{
  strokeWeight(1);
  line(x,y,x,y+length);
  strokeWeight(5);
  ellipse(x,y+length,size,size);
}


And here is our first interactive program:

void setup()
{
  size(300,300);
  background(0);
}
 
void draw()
{}
 
void mousePressed()
{
  println("x:" + mouseX + ", y:" + mouseY);
}

Exercise 4

Create a program where a unique shape follows the mouse position. When you click the mouse, the should change in some way (form, colour, size).