Skip to content

Instantly share code, notes, and snippets.

@stipebosnjak
Created November 2, 2018 02:06
Show Gist options
  • Save stipebosnjak/628fe4e222062985172fa46246fc819b to your computer and use it in GitHub Desktop.
Save stipebosnjak/628fe4e222062985172fa46246fc819b to your computer and use it in GitHub Desktop.
Unity 3D boxgeneration algorithm - random bottom -> top
public void GenerateCrates(int crateCount)
{
var crateSize = Crate.GetComponent<BoxCollider>().size;
var bounds = SpawnBounds.bounds;
var maxCrates = bounds.size.x * bounds.size.z * bounds.size.y;
Assert.IsFalse(crateCount > maxCrates, "Cargo hold cant hold that much crates!");
var bottomMin = bounds.min + crateSize / 2;
var possiblePositions = new List<Vector3>();
for (var x = bottomMin.x; x < bounds.max.x; x = x + crateSize.x)
{
for (var z = bottomMin.z; z < bounds.max.z; z = z + crateSize.z)
{
for (var y = bottomMin.y; y < bounds.max.y; y = y + crateSize.y)
{
possiblePositions.Add(new Vector3(x, y, z));
}
}
}
var positionsToGenerate = new List<Vector3>();
for (int i = 0; i < crateCount; i++)
{
var nextPosition = possiblePositions[Random.Range(0, possiblePositions.Count - 1)];
nextPosition = possiblePositions.Where(pos => pos.x == nextPosition.x && pos.z == nextPosition.z)
.OrderBy(x => x.y)
.FirstOrDefault();
positionsToGenerate.Add(nextPosition);
possiblePositions.Remove(nextPosition);
}
foreach (var position in positionsToGenerate)
{
Instantiate(Crate, position, Quaternion.identity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment