views:

214

answers:

1

How to stop MCs from overlapping each other?

private function loadWishes():void {



for (i; i<myXMLList.length(); i++) {
    cBox=new MovieClip();
    checkOverlap(cBox);
    addChild(cBox);
    commentArray.push(cBox);

   }
  }
  private function checkOverlap(wishB:MovieClip) {
   wishB.x=Math.random()*stage.stageWidth;
   wishB.y=Math.random()*stage.stageHeight;
   for (var i:uint=0; i<commentArray.length; i++) {
    if (wishB.hitTestObject(commentArray[i])) {
     checkOverlap(wishB);
     return false;
    }
    trace(commentArray.length);
   }
  }

This doesn't seems to be working cause the amount of it checking whether MC is overlapping is about the amount of MC on stage. how to make it keep checking till everything's fine?

A: 

The code you have here should work in general for preventing overlapping (though you should be careful - in a worst-case scenario this code might loop infinitely if the clips are too big or the stage is too small).

However, your problem is that you're calling this code on newly-created MovieClip objects, which are empty - so they can never overlap. Presumably you're adding in some child contents to the clips later, and at that point they overlap. So the fix is, you should populate the clips first, before checking if they overlap, or alternately, if you know the size of the clips, then instead of calling hitTestObject you could manually check whether the clip's position is too close to other clips.

fenomas
i think the code does not calculate on the width of the object that is called. So the 3rd object that is being loaded will be overlapping other MC.
Hwang
I see the problem now.. editing my answer.
fenomas