- Home /
How to instantiate objects in a circular formation?
Greetings,
I'm trying to instantiate objects in a circular formation in Unity2d.
I got the following code
private void SpawnCircleFormation()
{
Vector2 centerPosition = new Vector2(0,0);
float radius = 1.5f;
for (int i = 0; i < 360; i += 30)
{
Vector2 spawnPosition;
spawnPosition.x = (radius * Mathf.Cos(i)) + centerPosition.x;
spawnPosition.y = (radius * Mathf.Sin(i)) + centerPosition.y;
Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
}
}
The result i get is the following:
Which is not convenient. I wish to have the same distance between each instantiated object.
any advice?
Hi, sorry to disturb, is there a way where i can make it into a pyramid formation? like in a pool game where the 15 balls will be in a triangle formation kind of thing, im rather new to unity, so i would appreciate explanation too :D
Not at all,
Im not next to the pc once I get there I’ll draft a code that might help you.
:)
You mean arranged like a Pascal's triangle? This has little to do with a circular formation. Please ask a seperate question. We can not post an answer for your question here since that was not the question that was asked here. Comments are not meant for answering completely different questions. Since you already bumped this question you can leave a link to your question here.
Answer by UnityedWeStand · Aug 01, 2020 at 09:34 PM
Mathf trig functions expect the input to be in radians, not degrees. Substitute the input with i * Mathf.Deg2Rad
and you should be good to go.
Great!!!
thanks man.
i thought its expecting degrees. a shortco$$anonymous$$g from my part.
The last working solution for whoever searches this :)
private void SpawnCircleFormation()
{
Vector2 centerPosition = RandomizeSpawnPosition();
float radius = 1.5f;
for (int i = 0; i < 360; i += 30)
{
Vector2 spawnPosition;
float angle = i * $$anonymous$$athf.Deg2Rad;
spawnPosition.x = (radius * $$anonymous$$athf.Cos(angle)) + centerPosition.x;
spawnPosition.y = (radius * $$anonymous$$athf.Sin(angle)) + centerPosition.y;
Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
}
}