Processing Intro #02 | Function – Random Walk
Contents
- Random Walk
- Initial Setup
- Loop
- Function
- Concept
- Declaration/ Arguments / Return
- Usage
- Practice – Multiple Random Walks
- Random walk with function
- Initial Setup
- 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; }