Interaction Design WikiCreative Coding

Events und Functions (en)

deutsche Version

Functions are an elementary part of programming languages. With them, programs can be simplified and presented in a manageable and reusable way (modularisation). Functions also help us to keep our code organised and understandable. 

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 Processing 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 events can be intercepted. To do this, we only need to write functions (with names defined by processing) that are called automatically for the respective events.

Let's take the Example 1 and expand it to use events:

int length1 = 0;
int length2 = 0;

void setup() {
  size(300, 300); // define window size
  background(0); // define background colour
  stroke(255, 255, 255); // define line colour
}
void draw() {
  background(0);
  length1 = mouseX;
  length2 = mouseY;
  line(100, 10, 100, length1); // draw a line
  line(150, 10, 150, length2);
  line(200, 10, 200, 250);

  fill(0, 0, 0); // fill colour
  strokeWeight(5); // line thickness
  ellipse(100, length1, 50, 50); // draw an ellipse
  ellipse(150, length2, 50, 50); // draw an ellipse
  noFill(); // turn off fill
  ellipse(200, 250, 50, 50); // draw an ellipse
}


In this program we use two special functions:

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 (this will make more sense when we look at writing our functions). Processing calls the setup functions as soon as the program starts, and the draw function every time the screen refreshes. We will use these two functions for all of our future processing sketches.  

Exercise 3:

Take your results to form exercise 2, and modify it so it animates across the screen.