- Home /
Question by
bteo10 · Apr 18, 2019 at 08:46 PM ·
collidercollidersoverlapoverlapsphereoverlapping
Objects overlapping at origin (0,0,0) (question about OverlapSphere?)
I create spheres in random positions in a disk form. And I don't want them to overlap. So I use OverlapSphere before I create every sphere to generate an array of colliders that overlap with my sphere. The OverlapSphere position is set to the sphere position which is not at origin.
But after I create some spheres without problems in different positions, there is an overlap with colliders from ALL SPHERES at origin (I realized this after debugging). Wtf. Please tell me what I'm doing wrong cause I haven't found a solution anywhere. I'm a beginner so maybe it's something simple I'm missing...
My code:
public class Universe : MonoBehaviour { public int numberOfStars = 300; public int maxRadius = 100;
void Start()
{
for (int i = 0; i < numberOfStars; i++)
{
//creating cartesian coordinates / position
float distance = Random.Range(0, maxRadius);
float angle = Random.Range(0, 2 * Mathf.PI);
Vector3 cartPosition = new Vector3(distance * Mathf.Cos(angle), 0, distance * Mathf.Sin(angle));
//array of colliders which overlap with the star
Collider[] positionCollider = Physics.OverlapSphere(cartPosition, 5f);
//checking if there's overlap
if(positionCollider.Length == 0)
{
//creating the star if there is no overlap
GameObject starGO = GameObject.CreatePrimitive(PrimitiveType.Sphere);
starGO.transform.position = cartPosition;
Debug.Log("Star created.");
}
else
{
//try another position if there is overlap (try again)
i--;
Debug.Log("Oops.");
}
//but the array of colliders consists of colliders from ALL THE STARS created before...
}
}
}
Comment