Spawning prefabs randomly within a rectangle
Hi, I am working on a space shooter game and I want to instantiate about 3-5 prefabs (enemies) that don't overlap each other within the space of a 2D rectangle (with their positions rounded to int since it's more of a grid based game)
The rectangle (enemy formation) would move down slowly and a new formation would be instantiated once every 5 seconds. Would really love some help on this as I've been stuck on this for a while. Thank you.
Answer by UnityCoach · May 09, 2017 at 12:50 AM
You want to define an area to spawn within. Using a rect, or better a RectTransform will do it perfectly. Then, you generate a random position with that rectangle, and you can measure the distance between the position you find and other positions to make sure they're far enough from each other. You can use .RoundToInt()
to round a float to an int.
I touch on this, amongst many other things in my training course.