开发者

Random position without overlapping

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 amou开发者_如何学Cnt 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜