...
Functions act as jumps in the program. In the event of a function call, the program jumps to the position where the function is defined and then returns after the function has been executed. Most programming languages have many built in or native functions. To find out how the functions work, and what parameters they expect, we need to look at the processing documentation (https://processing.org/reference/).
In the previous examples we have written programs without functions. These programs were not interactive and do not include animations. So how can you extend a program so that, for example, the keyboard is used as an input? The answer is to use program events, which are recorded and forwarded by the program. Here is a short list of some such events:
...
These functions accept no parameters so the space between the brackets is left blank, and they have no return value so the 'void' keyword is used. The function names are reserved names that Processing knows, Processing calls these functions as soon as the corresponding event occurs.
Further functional examples
This example shows how to write functions with return values.
Code Block |
---|
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 around the code of legible and simple blocks (modularization).
Code Block |
---|
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:
Code Block |
---|
void setup()
{
size(300,300);
background(0);
}
void draw()
{}
void mousePressed()
{
println("x:" + mouseX + ", y:" + mouseY);
} |
Exercise
Create a Programm where a unique shape follows the mouse position.