I am trying to use random unitinsidesphere, to spawn some gameobjects that are Non-Kinematic and have sphere colliders on them. I want to spawn them in this visual sphere I have (no collider), which, obviously is no problem.
But I don’t want them to be able to spawn in eachother. Now, a way I’ve done a “spawncheck” on something else, was to use an empty gameobject with a non kin rigidbody and a collider, move it to where I am trying to spawn, and check if anything is in the collider. If not, sure, if not find another spot in that area, until you get a good spot.
I was thinking of doing the same thing here, but I want to know really I guess if that is even optimal. If not, does anybody have a better way to do it?
-Thank in Advance!
If you are only concerned about the spheres overlapping each other I can think of three approaches:
- Your current way checking colliders. Instead of using an empty game object just spawn the sphere and move it if it collides, until you find an empty spot. Performance will degrade as the space fills up… to optimise a little you can try to ‘repair’ positions by moving back
a.radius+b.radius
in a-b
direction… if no collision use that spot otherwise generate a new random position.
- If the spheres you are creating are of equal radius: as you create them store the origins in a list. New positions must be > 2xRadius from all points in this list. If it isn’t you can first try repair => move the point back along the origin->origin vector by the overlap distance (or a random amount >= the overlap distance) then check vs origin list again. When a suitable position is found create the game object. If you have a lot of objects to place you can use a quadtree to spatially subdivide and only check against existing objects in neighboring quadrants.
- 3D hex grid for the win! Divide your spherical bounds into a grid of origins 2r distance from each other (think marbles completely filling a round glass bowl). Then you need only a random integer [0,grid size) and can place your spheres guaranteeing no collision by blocking populated indexes (again you can repair by moving in a random direction until a free slot if there is a clash). This is also only suitable if the spheres you are spawning are of equal radius. It also results in a more regular positioning that isn’t as purely random, although this will not be very obvious for sparse arrangements.