Fractal Tree - Recursion
As a little programming challenge I wanted to program a fractal tree including parameters that can be changed during run time.
Changing the lines
void CreateLineSegment(int iterationStep, Segment lastSegment, int positiveNegative){
//Leave after the last iterationstep has been reached.
if (iterationStep > iterations)
{
return;
}
//Instantiate a line.
GameObject currentInstance = Instantiate (linePrefab,lineParent.transform);
currentInstance.name = "Line_" + iterationStep.ToString ();
//Get the Segment class of the instantiated Line.
Segment currentSegment = currentInstance.GetComponent<Segment> ();
/*Set the last Segment class, wether its positive or negative (angle) and the iterationStep.*/
currentSegment.lastSegment = lastSegment;
currentSegment.positiveOrNegative = positiveNegative;
currentSegment.iterationIndex = iterationStep +1;
/*Update the iterationStep and call the Function again. Once positive and negative.*/
iterationStep++;
CreateLineSegment (iterationStep, currentSegment, 1);
CreateLineSegment (iterationStep, currentSegment, -1);
Instantiating the lines
void Update(){
//Leave after the last iterationstep has been reached.
if (lastSegment == null) {
startPosition = Vector2.zero;
lineLength = FractalTree.staticInstance.startLength;
direction = Vector2.up;
endPosition = direction * lineLength;
} else {
startPosition = lastSegment.endPosition;
lineLength = FractalTree.staticInstance.startLength/iterationIndex;
direction = Quaternion.Euler (0f, 0f,
(FractalTree.staticInstance.startAngle) * positiveOrNegative) * lastSegment.direction;
endPosition = startPosition + direction.normalized *lineLength;
}