I have multiple objects that appear randomly on stage, but i want them to never touch each other when they appear.
object1.x = Math.random() * stage.stageWidth;
object1.y = Math.random() * stage.stageHeight;
object2.x = Math.random() * stage.stageWidth;
object2.y = Math.random() * stage.stageHeight;
object3.x = Math.random() * stage.stageWidth;
object3.y = Math.random() * stage.stageHeight;
etc...
And also how can i make them appear inside a box, instead of the stage.
They obviously can't appear at random then.
A naive but quick to code solution is to use bounding box collision before actually placing the element using:
If there is indeed a collision you can re-run the random placement of that particular element until there is not any collision.
This method is naive because you need to run the collision detection for all elements on your screen each time you are attempting to do a random placement. If it fails (meaning there is a collision), then you need to run it again until there is not.
Keep in mind that you can also pre-calculate the placements instead of checking on animation runtime (if it's an animation).
For the second part of you question.
Instead of using the
stageWidth
as a placement variable, you can use a function that returns a random integer within a range.The ranges provided would be:
..of the box you want to constraint your elements in.
The function would return a random integer within those ranges and your boxes would always fall within that box.
Here's a code snippet to get you started: