The Fractal Branch
      
by ilyas usal

Now that we have the function, the bulk of the work is done. All we have to do is call it recursively. But let's not go too fast. First we'll do the recursion "by hand".

[ keep clicking the above animation to create the branch ]

The code for the above example is:

s_x = 200 ; // starting _x position
s_y = 350 ; // starting _y position
s_l = 100 ; // starting length
s_a = -Math.PI/2 ; // starting angle
s_s = 10 ; // starting size

function makeBranch (start_x, start_y, length, angle, size) {
this.lineStyle ( size, 0x333333, 100 ) ;
this.moveTo ( start_x, start_y ) ;
var end_x = start_x + length * Math.cos ( angle ) ;
var end_y = start_y + length * Math.sin ( angle ) ;
this.lineTo ( end_x, end_y ) ;
s_x = end_x ;
s_y = end_y ;
}

this.onMouseDown = function () {
makeBranch ( s_x, s_y, s_l, s_a, s_s ) ;
s_l *= 0.8 ;
s_a += Math.PI/16 ;
s_s -- ;
}

I've added a few hard-coded value at the beginning of the code. I set the starting angle to -Math.PI/2 because it is a tree after all, and trees usually go up, but you can change that if you want to give your tree a funny angle.

Then inside the makeBranch function, I added 2 lines that update the s_x and s_y variables. By doing that, I say that the starting position of the next branch will be the ending position of the current branch.
 
At the end of the script, I say that when the user presses the mouse button, I want Flash to draw a branch, then shorten the length of the branch, increase its angle, and decrease its size.

You may have noticed that we didn't set any condition to stop the loop. That's because properly speaking, there's no recursion yet. To create an infinite loop, you'd have to click the mouse button several thousands of time within the same frame, which is... highly improbable.

Ilyas Usal
{Pictures 1 | 2}

 



SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.