I’ll elaborate a little, but the concept is pretty simple.
If you are placing a circle A on the screen and all you have on the screen are circles, you simply randomly choose a position and a radius for your ‘to be placed’ circle, then check all other circles to see if they will be less that Circle A radius + Circle B radius apart. If you find a case where there is overlap, choose new coordinates. This IS NOT EFFICIENT, but it is the base case from which all other test-then-place solutions can be derived.
What about rectangles? Easy, Treat all rectangles like circles, where the radius of the circle is half the length of the longest side of the rectangle. i.e If a rectangle is wider than it is tall, then the radius of the circle representing its overlap space is width/2.
What about polygons? These are the most difficult, but still quite simple. Just plug the vertices into some math and calculate:
- centroid of shape (x,y position of center)
- maximum distance on shape from centroid (this is your radius).
Are there other ways?
There are tons of ways:
- Instead of treating all shapes as circles, if your shapes are all rectangles you can apply rectangle versus rectangle overlap tests (search for the math on this. I’m sure Lua based solutions exist.)
- Alternately, you can check the points of shapes’ vertices to see if lie inside other shapes.
If you get really good at this, and if you have a restricted set of shape types, you can actually spend some time refining the math to get the most optimal checks and save computing time.
Are there even more ways?
- Avoid the whole problem and come up with clever placement and tracking rules of your own.
The point is, there are dozens and dozens of ways to do this, so I find it unlikely you’ll get a ‘one-size fits all’ solution that is perfectly optimal for all cases here. However, you can start off simple, dig into the math, and come out the other side with some fine knowledge and some cool solutions.
PS - You’ve got my code for the circle test and it’s pretty simple so I suggest that as a starting point. Pay close attention to the fact that I quit looking if I can’t find a free spot within a reasonable number of tries.