I have multiple objects that appear randomly on stage, but i want them
to never touch each other when they appear
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:
// http://stackoverflow.com/questions/2752349/fast-rectangle-to-rectangle-intersection
function rectIntersection(r1,r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
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.
And also how can i make them appear inside a box, instead of the
stage.
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:
- top-left/top-right for width
- bottom-left/bottom-right for height
..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:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}