- Home /
Random position without overlap. HELP!
I need a JavaScript coding reference on how to randomly position several objects (8 to 10 objects) on a specific 2D area without overlapping them. Once one of these objects gets a mouse click it would reposition itself onto a new random position (within the same area, without overlapping the other objects). I am fairly new to coding and this is one of my practice exercises. I would be really glad if someone could help me out with this, I've done courses and have been researching for a long time to get this right... with no success...
You could place all the object in an array then cycle through them and use the Random function (http://docs.unity3d.com/ScriptReference/Random.Range.html) to place them in a certain range on a 2d plane.
Answer by smoggach · Aug 13, 2014 at 01:28 PM
There are much more elegant ways to do it but the most obvious way to me would be some code that follows this logic: 1. pick a random position 2. perform a boxcast the same size as your object on that position 3. place your object if there are no hits 4. if there are hits then choose a new random position and repeat
The problem I've have with this is there's always some way to position the first N-1 objects so the last one won't fit, or will fit in only a very small area.
So, you limit to 50 tries and take the last if none work. But the last is often a complete overlap with something else, so you have to keep track of the "best" (least overlappy) result as you go.
I've only gotten good results with this when there was a lot of extra space.
Your answer
Follow this Question
Related Questions
Spawn game object in random position on screen 1 Answer
Spawn GameObjects without overlap 1 Answer
Randomly generated number 0 Answers
How do I check if/where in a sprite another sprite is? 0 Answers