How can I randomise location of objects in a room?
Hi guys. What Im trying to do in the room I've created for the game is to have a desk randomly located in different locations in the room but to also have objects that may go inside or on top of the desk also randomly located in the room and if it is randomly located to go on top of the desk then It will be placed properly (have the correct x, y and z).
Thank you!
Answer by unity_HBBcWhhgydLATA · Jan 19, 2021 at 03:31 PM
I solved a similar challenge by first creating an empty sprite that I could size properly - It is used basically as a 'Spawn Area'. Then I can simply instantiate objects as parents of this sprite, position them based on parent bounds (both by spawn area bounds and placement object bounds), and finally un-parent placed objects from the spawn area.
Some code sample:
private void spawnOn(GameObject area, int amount, List<GameObject> items)
{
for (int i = 0; amount-- > 0; i++)
{
i = i > items.Count - 1 ? 0 : i;
GameObject enemyInstance = Instantiate(items[i]);
enemyInstance.transform
.SetParent(area.transform);
Vector2 spawnAreaExtents = enemyInstance.transform
.parent.GetComponent<SpriteRenderer>()
.bounds.extents;
spawnAreaExtents = spawnAreaExtents - (Vector2)enemyInstance.transform
.GetComponent<Collider2D>()
.bounds.extents;
enemyInstance.transform.position = new Vector2(
Random.Range(spawnAreaExtents.x, -spawnAreaExtents.x),
Random.Range(spawnAreaExtents.y, -spawnAreaExtents.y));
enemyInstance.transform.parent = null;
}
}