Skip to content

Instantly share code, notes, and snippets.

@pyrobot
Created December 10, 2013 19:23
Show Gist options
  • Save pyrobot/7896533 to your computer and use it in GitHub Desktop.
Save pyrobot/7896533 to your computer and use it in GitHub Desktop.
void spread(Transform area, ref GameObject[] array) {
int l = array.Length;
if (l > 1) {
Vector3 center = area.collider.bounds.center, extents = area.collider.bounds.extents;
float top = center.y + extents.y,
bottom = center.y - extents.y;
bool allSpread;
int tries = 0, maxTries = 5000;
float bumpDist = 1.5f;
do {
Array.Sort(array, delegate(GameObject x, GameObject y) {
return x.transform.position.y.CompareTo(y.transform.position.y);
});
allSpread = true;
for (int i = 0; i < (l - 1); i++) {
GameObject obj1 = array[i],
obj2 = array[i+1];
float dist = obj1.transform.position.y - obj2.transform.position.y;
if (Mathf.Abs(dist) < bumpDist) {
allSpread = false;
obj1.transform.position = new Vector3(center.x, UnityEngine.Random.Range(bottom, top), center.z);
}
}
if (!allSpread) {
tries++;
}
} while (tries < maxTries && !allSpread);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment