How to progressively draw a fractal tree

edited August 2018 in Questions about Code

Hi everyone, I need to do a school project and I want to build a fractal tree that progressively "grows" using the mouse. how can I do it? this is the code I built:

void setup() 



int levelsMin = 0;
    int levelsMax = 6;
    float initialLength = 235;

    float angleMin = PI/17;
    float angleMax = PI/10;

    int pointColor = color(27, 25, 9);

   void draw() {

        stroke(88, 50, 0);

        float currentAngle = map (mouseX, 0, width, angleMin, angleMax); //mouse control of the branch angle
        int currentLevels = (int)map (mouseY, height,0, levelsMin, levelsMax); //mouse control of the generations count

        pushMatrix(); //save the world transformation matrix
        translate (width/2, height); //move the origin to the middle / bottom
       albero (currentLevels, initialLength, currentAngle); //draw first two branches - stems
        popMatrix(); //return to the world coordinate system

    void albero (int levels, float length, float angle){
        if (levels>0){  //check if there are any levels left to render
            pushMatrix();           //save current transformation matrix
            rotate (angle);         //rotate new matrix to make it point to the right
            line (0,0,0,-length);   //draw line "upwards"
            pushMatrix();           //save current (e.g. new) matrix
            translate(0,-length);   //move the origin to the branch end
            scale (0.85f);          //scale down. fun fact - it scales down also the stroke weight!
           albero (levels-1, length, angle);  //call the recursive function again
            popMatrix();            //return to the matrix of the current line
            popMatrix();            //return to the original matrix
            //second branch - the same story
            rotate (-angle/1.7);
            line (0,0,0,-length);
            scale (0.85f);
            albero (levels-1, length, angle);




Sign In or Register to comment.