AS3 - How can objects that appear randomly never touch each other?

112 views Asked by At

I have two 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;
2

There are 2 answers

0
tziuka On

If you have only 2 objects that appears on the stage, then is easy. In EnterFrame event you just put an if condition

    if(!obj1.hitTestObject(obj2)) {
        obj1.x = Math.random() * stage.stageWidth;
        obj1.y = Math.random() * stage.stageHeight;
    }

but if you have many objects, then you have to loop through all the objects and check the same condition.

for(var i:int=0; i<yourObjNumber; i++) {
      var hits:boolean = false;
      if(!obj1.hitTestObject(getChildAt(i))) {
           hits = true;     
      }
      if(hits) {
            obj1.x = Math.random() * stage.stageWidth;
            obj1.y = Math.random() * stage.stageHeight;
      }
}

Hope this helps!

Have a great day!

0
Marty On

As @DodgerThud has mentioned; the way to go about this problem is to repeatedly attempt to place the next object until it meets your criteria (not colliding with another object). This is a perfect example of what a while loop can be used for, something like:

while (!object1.hitTestObject(object2))
{
    object1.x = Math.random() * stage.stageWidth;
    object1.y = Math.random() * stage.stageHeight;
}