Home > Enterprise >  How can I center GameObjects in Unity by X coordinate?
How can I center GameObjects in Unity by X coordinate?

Time:05-27

I have method which adds child cubes to gameobject with space between them.

public void AddElement()
{
    const int elementWidth = 1;
    const double space = 0.2;
    var elementsAmount = elements.Count;
    var xPosition = (float)(elementWidth   space) * elementsAmount;
    var position = transform.position;
    var e = Instantiate(elementToAdd, 
        new Vector3(xPosition, position.y, position.z), Quaternion.identity);
    elements.Add(e);
    e.transform.parent = transform;
}

Like this

But I can't understand how can I center the parent object after each call of AddElement() to make it look like this

There should be some offset to the left but how to calculate it?

CodePudding user response:

You must align the hand once after each instantiate. The following code aligns the list with the exact size and the problem is solved.

public void AddElement()
{
    const int elementWidth = 1;
    const double space = 0.2;
    var e = Instantiate(elementToAdd, transform);
    elements.Add(e);
    
    var totalWidth = (float) (elementWidth   space) * elements.Count;

    var step = totalWidth / elements.Count;

    for (var i = 0; i < elements.Count; i  )
    {
        var position = elements[i].transform.position;
        elements[i].transform.position = new Vector3(step * (i .5f) - totalWidth/2, position.y, position.z);
    }
}

CodePudding user response:

Well you can move the camera to the right or move all the objects at once. You're adding the element or block to the end well but, as you get more and more elements or blocks on the screen you'd have to shift them all in a for loop to the left. The psuedocode below explains a little bit of what I mean. You need half the total size of your blocks with spaces. Sub that from each block. Then re-add the block sizes and spaces based on which index they are. Starting at 0.

        float ttlSize = 0.0f;
        foreach (var ele in elements)
        {
            //ttlSize  = ele.x
        }
        float halfTtlSize = ttlSize / 2;
        for (int i = 0; i < amountOfBlocks; i  )
        {
            //ele.x = ele.x - halfTtlSize   ((elementWidth   space)*i)
        }
  • Related