Hi everyone,
i have the same problem as @Elfrick here:
The fix he was told uses cartesian coordinates, but i like to retain the orbital arrangement and want to know what I did wrong.
I tried many things, but i cant get the Collider to accept the variable, it seems to use (0,0,0) instead of the new coordinates. It should be impossible to have a sphere in the middle of the Collider, too, but there it is. The code should check the space around each sphere and prevent other spheres to be created near another sphere.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Galaxy : MonoBehaviour
{
// TODO: Have these values import from user settings
public int numberOfStars = 300;
public int maximumRadius = 100;
public float minDistBetweenStars;
// Start is called before the first frame update
void Start()
{
int failCount = 0;
for (int i = 0; i < numberOfStars; i++)
{
float distance = Random.Range(0, maximumRadius);
float angle = Random.Range(0, 2 * Mathf.PI);
var startPosition = new Vector3(distance * Mathf.Cos(angle), 0, distance * Mathf.Sin(angle));
// Vector3 startPosition = new Vector3(distance * Mathf.Cos(angle), 0, distance * Mathf.Sin(angle));
Collider[] positionCollider = Physics.OverlapSphere(startPosition, minDistBetweenStars);
if (positionCollider.Length == 0)
{
GameObject.CreatePrimitive(PrimitiveType.Sphere).transform.position = startPosition;
failCount = 0;
}
else
{
i--;
failCount++;
}
if (failCount > numberOfStars)
{
Debug.LogError("Could not fit all the stars in the galaxy. Distance between stars is too big!");
break;
}
}
}
// Update is called once per frame
void Update()
{
}
}
After changing the code to the one in the comments, i get this picture: