public class MapGenerator : MonoBehaviour
{
//start with constant number of planets
private const int numPlanets = 20;
//start with map size at 10 units
public static int mapSize = 10;
//sunPlanetSizeOffset is the difference in size between the sun and the planets
public float sunMaxSize, sunMinSize, sunPlanetSizeOffset;
public GameObject[] planets;
public GameObject[] suns;
private void Start()
{
//generate a sun
int randomSun = Mathf.RoundToInt(Random.Range(0, suns.Length - 1));
float sunScale = Random.Range(sunMinSize, sunMaxSize);
GameObject sun = Instantiate(suns[randomSun]);
sun.transform.localScale *= sunScale;
//generate planets
for (int i = 0; i < numPlanets; i++)
{
Vector3 initPos = new Vector3(0, 0, 0);
float planetScale = 1f;
bool isOverlap = true;
int safetyNet = 0;
while (isOverlap || safetyNet < 15)
{
initPos = generateInitPos();
planetScale = Random.Range(1f, sunScale - sunPlanetSizeOffset);
isOverlap = determineOverlap(initPos, planetScale);
safetyNet++;
}
if (!isOverlap)
{
int randomPlanet = Mathf.RoundToInt(Random.Range(0f, planets.Length - 1));
GameObject planet = Instantiate(planets[randomPlanet], initPos, Quaternion.identity);
planet.transform.localScale *= planetScale;
}
}
}
/// <summary>
/// determines if the chosen location is already occupied
/// </summary>
/// <param name="pos"></param> location chosen
/// <param name="radius"></param> radius for planet
/// <returns></returns> true if location is occupied, false otherwise
private bool determineOverlap(Vector3 pos, float radius)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(pos, 2 * radius);
return !(colliders.Length == 0);
}
private Vector3 generateInitPos()
{
float radius = Random.Range(1f, 8f);
float theta = Random.Range(0f, 2f * Mathf.PI);
float x = radius * Mathf.Cos(theta);
float y = radius * Mathf.Sin(theta);
return new Vector3(x, y, 0);
}
}
I’m trying to understand the best way to do procedural generation in Unity, and I feel like I’m almost there. In this example, I’m generating a solar system by first spawning a sun with random scaling at the middle of the map and planets with random positions and scaling across the map in a way where supposedly nothing is overlapping. At the moment, my planets seem to be respecting the other planet positions, but for some reason there’s still some overlap with my sun as seen in the attached image. Does anyone know what could be causing this? Thank you!