Reputation:
Score[i].transform.localPosition = new Vector3 (0.013F + i * 0.01F, 0.12F, 0.0F);
i * 0.01F ensures that the gameobjects don't instantiate on top of each other. It instantiates the next gameobject 0.01F to the positive x so that they are beside each other instead of on top of each other. For context, the gameobjects are models of numbers that represent a score.
I want to move the whole group of gameobjects to the negative x each time a new gameobject is introduced. As of now, the numbers start in the middle, and instantiate further and further right. I would like for the whole group to be shifted left by the same amount that they are currently being spaced apart to the right, in order for the whole group to be centred.
I tried this but it did not do what I want.
ScoreHandler.Score[i].transform.localPosition = new Vector3 ((- 0.01F + i * 0.01F) * - 0.01F, 0.12F, 0.0F);
Thanks for any advice.
Upvotes: 1
Views: 88
Reputation: 86
To answer your question directly using your current method, you need to multiply the negative offset (- 0.01F) by the number of scores you wish to display and divide by 2 (or *0.5) like the following:
ScoreHandler.Score[i].transform.localPosition = new Vector3 (-0.01F * ScoreHandler.Score.Length * 0.5F + i * 0.01F, 0.12F, 0.0F);
Of course you can collapse the *0.5 with the offset and use:
-0.005F * ScoreHandler.Score.Length + i * 0.01F
Upvotes: 1
Reputation: 3639
The easiest (and most logical) approach would be to spawn all the digits as children of your "number" object.
As they are children of your number, moving the number will move the children. As long as the number knows how many children it has, it can set its own position accordingly.
public class Number : MonoBehaviour
{
int numDigits;
public float digitWidth = 0.01f;
public void AddDigit(int d)
{
GameObject digit = Instantiate(...prefab for d...);
digit.transform.parent = this.transform;
digit.transform.localPosition = Vector3.right * (numDigits++ * digitWidth);
this.transform.localPosition = Vector3.right * (-0.5f * numDigits * digitWidth);
}
}
You can now put your number into another object that sits at the position you want your number to be centered on and voila.
Upvotes: 0