Processing Intro #02 | Function – Random Walk

Contents

  1. Random Walk
    1. Initial Setup
    2. Loop
  2. Function
    1. Concept
    2. Declaration/ Arguments / Return
    3. Usage
  3. Practice – Multiple Random Walks
    1. Random walk with function
    2. Initial Setup
    3. Loop

Random Walk

Initial Setup

int x,y,px,py;
float theta;

void setup(){
  size(500,500);
  px=width/2;
  py=height/2;
}

Loop

void draw(){
  theta = random(-PI,PI);
  
  x = px + int( cos(theta)*10 );
  y = py + int( sin(theta)*10 );
  
  line(px, py, x, y);
  
  px = x;
  py = y;
}

Function

Concept

Function is the advanced feature in programming and is useful to make scripts more smart. Function can combine a bunch of procedure into one simple command.

Declaration / Arguments / Return

The syntax to define functions is following:

void <function name>(<arguments data type> <arguments name>){...}

Following is the simplest example of function:

void addFunction(int x, int y){
  print(x+y);
}

Also you can make functions that can return values. Functions of this kind are something like components in Grasshopper. The syntax to define function with return is following:

<data type of return value> <function name>(<arguments data type> <arguments name>){
 ...
 return <value to return>;
}

Following is the example:

int addition(int x, int y){
  return(x+y);
}

Usage

Using function is very easy. Following is a example to use previous function:

addFucntion(1,2);

int x = addition(2,3);
print(x);

Practice – Multiple Random Walks

Random Walk with Function

int x,y,px,py;
float theta;

void setup(){
  size(500,500);
  px=width/2;
  py=height/2;
}

void draw(){
  drawRandomWalk();
}

void drawRandomWalk(){
  theta = random(-PI,PI);
  
  x = px + int( cos(theta)*10 );
  y = py + int( sin(theta)*10 );
  
  line(px, py, x, y);
  
  px = x;
  py = y;
}