Hello and thank you for clicking here. I’m in some trouble. My game requires units to move around in formation, and this is the function that creates the formation depending on how many units you have.
public List<Transform> LineFormation(int numberInFormation)
{
foreach (Transform child in transform) //destroy prevoius list of gameobjects so we do not add twice
{
Destroy(child.gameObject);
}
List<Transform> soldierPositions = new List<Transform>();
for (int i = 0; i < numberInFormation; i++)
{
//create a list of children that can be accessed in the next loop
GameObject position = new GameObject("position " + i.ToString());
position.transform.parent = transform;
soldierPositions.Add(position.transform);
}
int count = 0;
float offsetX = offset;
float offsetZ = offset;
foreach (Transform soldier in soldierPositions)
{
Vector3 position = gameObject.transform.position;
if (count == rowInt) //if we have 7 soldiers in a row, start a new row
{
count = 0;
offsetZ += offset; //add a new row
}
//alternate between placements of positive x and negative x
if (count % 2 != 0) //number is odd
{
position.x -= offsetX; //offset once to left
}
else
{
if (count == 0) //first soldier is always set to middle
{
//do nothing so first soldier is naturally set to middle, reset the X offset
offsetX = offset;
}
else //every even numbered soldier goes to right of middle
{
position.x += offsetX;
offsetX += offset;
}
}
position.z -= offsetZ;
soldier.transform.position = position;
count++;
}
return soldierPositions;
}
So if the rotation on the parent object is not zero at the time of the formation creation( which will happen often in my game) you will always get a wonky looking formation.
here is an example where I rotated the Parent Object 90 degrees from 0 and sure enough the formation lined up 90 degrees off of the parent because they were aligning to zero
This is an example of how it looks when the parent transform’s rotation is reset to 0 and how it should look no matter the rotation of the parent object at the call of my function.
If you read this far thank you, and looking forward to your ideas.