I’ve been mucking around with recursive objects (objects that upon instantiation create a new instance of themselves, in this case the instance is a child) to create a fractal generator. It works by creating a single instance of the branch class, which then results in the creation of the entire fractal via recursion based on some global parameters and limits to stop infinite recursion. The result is basically some cool patterns: http://morefigs.net/flash-fractal-generator/
The source for the Branch class is:
package fractal.assets {
import flash.display.Sprite;
import fractal.global.Globals;
public class Branch extends Sprite {
// CONSTRUCTOR
public function Branch(len:Number, rot:Number, col:uint):void {
rotation = rot;
// iterate global branch count
Globals.instance.branchCount += 1;
// draw self
graphics.lineStyle(1, col);
graphics.moveTo(0, 0);
graphics.lineTo(0, len);
// soft ends effect, alpha is cumulative via parents
if (len < 20) {
alpha = 0.95;
}
var kidBranchColor:uint = col;
// work out randomised color if needed
if (Globals.instance.colorSpread > 0) {
// read off r g b channels from col unsigned integer
var r:int = ( col >> 16 ) & 0xFF
var g:int = ( col >> 8 ) & 0xFF;
var b:int = col & 0xFF;
// add a random positive or negative drift to the r g b channels
r += Math.round((Math.random() - 0.5) * Globals.instance.colorSpread);
g += Math.round((Math.random() - 0.5) * Globals.instance.colorSpread);
b += Math.round((Math.random() - 0.5) * Globals.instance.colorSpread);
// ...with limits
if (r < 0) { r = 0 } else if (r > 255) { r = 255 };
if (g < 0) { g = 0 } else if (g > 255) { g = 255 };
if (b < 0) { b = 0 } else if (b > 255) { b = 255 };
// convert the r g b channels back to an unsigned integer
kidBranchColor = ( r << 16 ) | ( g << 8 ) | b;
}
makeKids(len, kidBranchColor);
}
// make child branches
private function makeKids(len:Number, col:uint):void {
for (var i:int = 0; i < Globals.instance.prob.length; i++) {
// if global limits not reached and probability of children is high enough
if ((Globals.instance.prob* > Math.random()) && (Globals.instance.branchCount < Globals.instance.maxBranches) && (len > Globals.instance.minLength)) {
addChild(new Branch(len * (Globals.instance.lengthFactor* + (Math.random() - 0.5) * Globals.instance.lengthFactorSpread * 2), (Math.random() - 0.5) * Globals.instance.angleBiasSpread * 2 + Globals.instance.angleBias*, col));
getChildAt(numChildren - 1).y = len;
}
}
}
// null all child branches
public function nullKids():void {
while (numChildren > 0) {
var child:Branch = getChildAt(0) as Branch;
child.nullKids();
removeChild(child);
child = null;
}
}
}
}