- Home /
Instantiating objects without overlapping
Hey all!
I am creating a script that spawns X amount of gameobjects which are different sizes (1x1, 1x2, 2x1) in a certain area at random x and y positions (z coordinate is the same). Now the problem is that I am trying to find a way to spawn them so that they don't overlap. I've spent quite a lot of time with this and haven't come up with a good and simple solution.
Any help would be greatly appreciated!
Answer by FWCorey · May 02, 2015 at 11:14 AM
You can create a list of Rect's for each rectangle you spawn and check the new ones with myrect.Overlaps(otherRect) for each rect in the list when you generate the random locations.
You can do this and immediately discard the random value and stop or in a for(){} loop that limits the number of attempts.
I did try this earlier and yes it does work but I'd like to find a way that doesn't require constantly randomizing a new location until a position without overlapping is found. Thanks for the answer though!
You can randomize once then quickly check the 8 cardinal offsets of that position (x - 1, y- 1; x, y -1 etc...) if it overlaps. That will stop you from looping as much if they are likely to be dense on the screen.