- Home /
Question by
ratchetunity · Aug 06, 2020 at 01:25 PM ·
positionvector3overlapvector3.positionmiddle
Instantiate Gameobjects in the mid position across several targets without overlap
Hi! I have a GameObJect which instantiates several spheres as children. What I'm trying to achieve is that those spheres are instantiated in the mid position across two targets without the spheres overlapping each other, but I must be missing something. This is my code:
public Transform[] targets;
public GameObject spherePrefab;
private int numberOfSpheres = 5;
private float spawnMaxPosition = 5f;
private float spawnMinPosition = 1.5f;
private void Start()
{
Vector3 targetsMidPosition = TargetsMiddlePosition();
for (int i = 0; i < numberOfSpheres; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(spawnMinPosition, spawnMaxPosition), Random.Range(spawnMinPosition, spawnMaxPosition),
Random.Range(spawnMinPosition, spawnMaxPosition));
GameObject instantiatedSphere = Instantiate(spherePrefab, spawnPosition, Quaternion.identity, transform);
instantiatedSphere.transform.position = transform.position + (targetsMidPosition - instantiatedSphere.transform.position) / 2f;
}
}
private Vector3 TargetsMiddlePosition()
{
Vector3 targetsMidPosition = Vector3.zero;
for (int j = 0; j < targets.Length; j++)
{
targetsMidPosition += targets[j].position;
}
targetsMidPosition = targetsMidPosition / targets.Length;
return targetsMidPosition;
}
Comment