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
1 2 3 4 5 6 7 8 | int x,y,px,py; float theta; void setup(){ size( 500 , 500 ); px=width/ 2 ; py=height/ 2 ; } |
Loop
1 2 3 4 5 6 7 8 9 10 11 | 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:
1 2 3 | 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:
1 2 3 | int addition( int x, int y){ return (x + y); } |
Usage
Using function is very easy. Following is a example to use previous function:
1 2 3 4 | addFucntion( 1 , 2 ); int x = addition( 2 , 3 ); print (x); |
Practice – Multiple Random Walks
Random Walk with Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |