Fork me on GitHub
← Back

Demo - Tree

Code

var MAX_DEPTH = 3;
function createTreeBranch(depth, parentBranch, parentBone) {
    if (depth > MAX_DEPTH) {
        return;
    }

    // increase the depth
    depth++;

    var depthLength = ((2 + (MAX_DEPTH - depth)) * 25);
    var depthThickness = ((1 + (MAX_DEPTH - depth)) * 4);

    var animation = jBone.addAnimation({ name: 'treeMovement' + parentBranch + '-' + depth, frames: 5, duration: 5000, looped: true });

    var ang = (depth * 10);
    var randAngle = ((ang * 0.5) - Math.floor(Math.random() * ang));

    // generate 0, 1 or 2 branches
    var numNewBranches = 2 + Math.floor(Math.random() * 2);
    var offsetDirection = 0;
    var deltaAngle = 35 + randAngle;
    for (var index = 0; index < numNewBranches; index++) {
        // special angle
        var newAngle = offsetDirection + ((deltaAngle * (numNewBranches - 1)) * 0.5) - (deltaAngle * index);
        var newParentBranch = parentBranch + '-' + depth + '-' + index;
        // create a new child bone to the parent bone, and call branch again
        var childBone = parentBone.addChildBone({ name: newParentBranch, x: 0, y: 0, angle: newAngle, length: depthLength + ((1 + (MAX_DEPTH - depth) * 10) - Math.floor(Math.random() * (1 + (MAX_DEPTH - depth) * 20))), thickness: depthThickness });
        if (depth > 2) {
            // end bone, add content
            childBone.addContent({ name: newParentBranch + 'content', type: 'image', content: './leafBunch.png', pivot: jBone.Point(39, 31), offset: jBone.Point(0, 10), transform: jBone.Transform(0, 0, -45, 1) });
        }
        createTreeBranch(depth, newParentBranch, childBone);

        // add animations for the tree branches that have already been added
        animation.at(0)
                .rotate(newParentBranch, 0)
             .at(1)
                .rotate(newParentBranch, (randAngle * 0.25))
             .at(2)
                .rotate(newParentBranch, 0)
             .at(3)
                .rotate(newParentBranch, -(randAngle * 0.25))
             .at(4)
                .rotate(newParentBranch, 0);
    }
}

var root = jBone.addBone({ name: 'root', selectorId: 'treeDemo', angle: 90, length: 100, thickness: 20 });
createTreeBranch(0, '0', root);

jBone.render();