I’m doing an L-System algorhithm with Unity, and want it to grow instantiating copies of the same object. By the other hand, each object slowly scales up, too.
I want each object to stay next to the others, but not invading their space volumes. How can i do that?
The code of the objects is as follows:
void Start ()
{
iterations = 0;
transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); // The initial scale.
}
void Update ()
{
// Every copy of the object creates one single clone:
if (iterations < 90) { iterations++; }
if (iteraciones == 90)
{
Instantiate(object1, new Vector3(0, (transform.localScale.y) + transform.localPosition.y, 0), new Quaternion(0, 0, 0F, 0));
// This is in fact, the stop condition for instatiating objects.
iteraciones = 100;
}
// Each object scales up during its lifetime:
transform.localScale += new Vector3(0.0001f, 0.001f, 0.0001f);
}
I realize that somewhere in the code, i must refresh the position of the copied object to maintain the distance to the ‘father’s’ edge, or to his center position, or somewhat.
Any help is pretty appreciated
Doing an 3D L-System is a cool idea. You are going to need to figure out position and rotation to put objects end to end. Here is a bit of code as a demo. Put it on an empty game object and hit the space bar for each new segment. This is not code related to your script. It is a demo script that you can play with and work to understand, and then apply the concepts to your code:
#pragma strict
private var maxAngle = 45.0;
private var currScale = Vector3(0.25,0.5,0.25);
private var scaleBy = 0.8;
private var lastPos : Vector3;
private var lastDir : Vector3;
private var objectHeight = 2.0; // Height of object when scale is (1,1,1)
function Start() {
lastDir = Quaternion.AngleAxis(Random.Range(-maxAngle, maxAngle), Vector3.forward) * Vector3.up;
lastPos = transform.position;
}
function Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
sphere.position = lastPos;
if (scaleBy >= 1.0)
sphere.localScale = Vector3(currScale.x, currScale.x, currScale.x);
else
sphere.localScale = Vector3(currScale.x / scaleBy, currScale.x / scaleBy, currScale.x / scaleBy);
var v = lastDir;
v = Quaternion.AngleAxis(Random.Range(-maxAngle, maxAngle), Vector3.forward) * v;
v = v.normalized * currScale.y * objectHeight;
var endPos = lastPos + v;
var cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder).transform;
cylinder.localScale = currScale;
cylinder.position = lastPos + v * 0.5;
cylinder.rotation = Quaternion.FromToRotation(Vector3.up, v);
lastDir = v;
lastPos = endPos;
currScale *= scaleBy;
}
}