(10) Fun with recursive function - Classic tree

One way to write very short programs that can make up complex drawings is to use recursive calls to a function. A recursive function is a function that calls itself from inside the own code in the function. When this is done, it is extremely important to have a termination condition to stop doing that. Otherwise the function will end up locking up the program/computer and will not respond at all.

A very classic example of this is to draw a "tree". This is done by drawing a line, just a line in a function, but then in the call, calling itself again twice. The call to itself is then modified to have a slightly shorter line, and at an angle... Enough talk. This is about "learn by doing". Here is the code:

// Run once
void setup() {
  // size(1000, 1000);

// Run "frameRate" times per secont
void draw() {
  // angle is the amount of tilt we do on the line. 
  // In radians : 2*PI radians = 360 degrees 
  float angle = (width/2-mouseX)*TWO_PI/width;
  // len is the length of the first line
  float len = (height-mouseY)/2;
  background(0); // Black
  stroke(255);   // White
  // Print the text
  text("Len = " + len + " Angle(radians) = " + angle, 15, 15);
  // Call the tree function (once)
  tree(width/2, height, len, -PI/2, angle);

// This is the recursive function
void tree(float x, float y, float len, float alpha, float gamma) {
  line(int(x), int(y), int(x+len*cos(alpha)), int(y+len*sin(alpha)));
  // We need to have some termination condition. In our case we stop 
  // Calling recursive once the length has decreased to 1 
  if (len>1) {
    // We change the len and alpha for each call to make up the "tree"
    tree(x+len*cos(alpha), y+len*sin(alpha), len*0.64, alpha-gamma, gamma);
    tree(x+len*cos(alpha), y+len*sin(alpha), len*0.64, alpha+gamma, gamma);

Now, some math understanding is required to really see what is going on, but please just copy, paste and run. Move the mouse! Read the text! Have fun!

No comments:

Post a Comment