Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Fractal Branch: Example

by ilyas usal   | filed under Flash and ActionScript

This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.

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}

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.

Your support keeps this site going! 😇

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--