Search code examples
c#unity-game-enginefractals

How is localScale reducing in this Fractal code sample for Unity


I am following this Unity Fractal example:

http://catlikecoding.com/unity/tutorials/constructing-a-fractal/

using UnityEngine;
using System.Collections;

public class Fractal : MonoBehaviour {

    public Mesh mesh;
    public Material material;
    public int maxDepth = 20;
    public int depth = 0;
    public float childScale = 0.5f;

    // Use this for initialization
    void Start () {
        gameObject.AddComponent<MeshFilter>().mesh = mesh;
        gameObject.AddComponent<MeshRenderer>().material = material;
        if(depth < maxDepth)
        {
            new GameObject("Fractal Child").AddComponent<Fractal>().Initialise(this);

        }
    }

    // Update is called once per frame
    void Update () {

    }

    private void Initialise(Fractal parent)
    {
        Debug.Log(gameObject.transform.localScale);
        mesh = parent.mesh;
        material = parent.material;
        maxDepth = parent.maxDepth;
        childScale = parent.childScale;
        Debug.Log("childScale = " + childScale);
        depth = parent.depth + 1;
        transform.parent = parent.transform;
        transform.localScale = Vector3.one * childScale;
        Debug.Log("localScale = " + transform.localScale);
        transform.localPosition = Vector3.up * (0.5f + 0.5f * childScale);
    }
}

Up to this point I do have a vertical stack of boxes on top of each other, where each box is half the size of the box below it (childScale is set to 0.5f).

What I don't quite get is why each gameobject (Fractal instance) is half the size of its parent. childScale is always 0.5f, I dont see how it would reduce to 0.25f, 0.125f etc in this code to make each instance which is recursively created - half the size of it's parent.

Any advice appreciated.

Image below is result (note that this is using a childScale of 0.9f not 0.5f).

enter image description here


Solution

  • The scale shown in the editor is local scale. Local scale is relative to the transforms parent. The fractal example is nested. So if your top level parent is .5 local scale, it's also .5 world scale since it has no parent. Your next object down is .5 local scale, but (.5 * .5) world scale. Next object down is .5 local scale, (.5 * .5 * .5) world scale. See where this rabbit hole is going? :)