- Home /
How to Make an Expanding Spawn Area for Prefabs?
Hello, everyone. I am making a game where I want some prefab cubes to be continuously spawned around a bigger cube; kind of like the rings of a planet. The problem is: the bigger cube is continuously growing in size, therefore more objects must be spawned around a larger area/circumference. How would I do this? (possibly an expanding ring shaped spawn area?) Thanks!
Answer by ahstein · Jun 26, 2018 at 08:21 PM
Define your spawn region in polar coordinates (radius, angle) around the center of your cube. Spherical coordinates if you're working in 3D. You can easily expand the radius to be either the size of the cube times some factor or plus some factor. You can spawn at random angles or according to some pattern.
You'll need to include a conversion from polar/spherical coordinates to Cartesian coordinates, though.
Vector2 PolarToCart (float r, float theta) {
return new Vector2(r * Mathf.Cos(theta),
` r* Mathf.Sin(theta));
}
Vector3 SphericaltoCart (float r, float theta, float phi) {
return new Vector3(r * Mathf.Cos(theta)*Mathf.Sin(phi),
r*Mathf.Sin(theta)*Mathf.Sin(phi),
r*Mathf.Sin(phi));
}
@ahstein so how exactly would I define all this stuff and implement it into the game? i'm rather new to c#, so some details or example code would be nice :)
// attach this to the parent object
class Spawner : $$anonymous$$onobehavior {
public GameObject prefabToSpawn;
public float parentSize; // if you changing the size of the cube using it's transform's scale, this is unnecessary, you can just use that ins$$anonymous$$d.
// spawns prefabs every 30 degrees in a circle around the parent. The radius of the circle is 20% larger than the parent's size.
void SpawnInCircle() {
float radius = parentSize * 1.2f;
for(int theta = 0; theta < 360; theta += 30) {
Vector3 location = SphericalToCart( radius, theta, 0);
GameObject newSpawn = Instantiate(prefabToSpawn, location, Quaternion.identity);
newSpawn.transform.parent = transform;
}
}
Vector3 SphericalToCart (float r, float theta, float phi) {
return new Vector3(r * $$anonymous$$athf.Cos(theta)*$$anonymous$$athf.Sin(phi),
r*$$anonymous$$athf.Sin(theta)*$$anonymous$$athf.Sin(phi),
r*$$anonymous$$athf.Sin(phi));
}
}
@ahstein so how would I replace parentSize with transform.localScale?
Answer by Trevdevs · Jun 27, 2018 at 03:00 PM
If these cubes are purely aesthetic and don't need to be interacted with you could use a particle system and under the velocity tab play with the orbital velocity.
Here's a video that demonstrates it :)
Your answer
Follow this Question
Related Questions
instatiates at a bad position 1 Answer
How Do I Add An Instantiated Object To An Array? 3 Answers
How to prevent multiple spawns from a single spawn point? 1 Answer
Having Trouble with Instantiating an object on an axis 2 Answers
How would I create a script that spawns objects more frequently as time goes on? 3 Answers