- Home /
Spawning multiple objects in same area without intersecting each other
I want to spawn/instantiate a group of objects around a spawner. The problem is, I don't want them to occupy the same space. If I use rigid bodies and colliders and let the physics system figure out the position (by spawning them all on top of each other) then they fly off in two directions due to some force applied.
To help visualize what I'm trying to accomplish, picture the following horrible ASCII art:
A = spawner
B = unit 1
C = unit 2
D = unit 3
Scenario 1:
BBCC
ABCC
BBCC
CCCC
Scenario 2:
CCBBBA
CCBBB
CCBB
CCBB
DDA
DD
The goal is to instantiate these objects as a group, multiple objects acting as one. The problem I have is I have no idea how to determine what areas are free. I'm working with cubes so I don't know if OverlapSphere will work properly as it might create too big of gaps between the units. If you need more detail from me or better descriptions of the goal, let me know and I'll see what I can do. I've spent the past few hours hunting through documentation, tutorials and examples trying to figure out how to accomplish this but it seems the only answers I've found are manually placing them in the editor or spawning them as a circle (which ignores existing objects).
I was hoping that by using rigid bodies/colliders I would let the physics engine sort of nudge them into an orderly position, but that didn't exactly go as planned. Another idea was to get the position and size of the spawner and spawn a unit by doing a raycast in a cardinal direction, finding an empty space and then placing the unit there. Then to spawn the next unit, I'd raycast from the first unit and find an empty space. The problem with that is I don't know if that kind of raycasting is expensive and what to do if the spawner is completely surrounded (the units should still spawn, see the C units in Scenario 1). The only thing that should prevent the units from spawning would be a hard limit on how many can be on the map or in a highly unlikely scenario, if there's no room on the map.
If the ASCII art above isn't descriptive enough, I'll throw something together in paint. I'm not an artist, sadly, so I'm working with programmer art (or lack thereof).