[ActionScript 3.0] AS3.0 对象在一定范围随机显示不重叠

import flash.geom.Rectangle;
import flash.display.MovieClip;
import flash.display.Sprite;

var arr:Array = [];
var dis:Number = 20;//间距
var len:int=15;//对象数量
var bound:Rectangle = new Rectangle(0,0,1000,800);//显示范围
for(var i:int = 0;i<len;i++){
    var obj:Sprite = new Sprite();
    obj.graphics.beginFill(0xcccccc);
    obj.graphics.drawRect(0,0,120,100);
    obj.graphics.endFill();
    obj.name = "obj_"+i;
    arr.push(obj);
    this.addChild(obj);
}
reset();
function reset():void{
    for(var j:int = 0;j<len;j++){
        setPosition(this.getChildByName("obj_"+j) as Sprite);
        //test(this.getChildByName("obj_"+j) as Sprite);
    }
}
function setPosition(obj:Sprite):void
{
    obj.x = Math.random()*(bound.width-obj.width)+bound.x;
    obj.y = Math.random()*(bound.height-obj.height)+bound.y;
    for(var i:int = 0;i<arr.length;i++){
        if(obj != arr[i]){
            //不重叠,没有间距
            /*if(obj.hitTestObject(arr[i])){
                setPosition(obj);
                return;
            }*/
            //不重叠,并有一定间距dis,间距为0效果同上
            if(Math.abs(obj.x-arr[i].x)<obj.width+dis&&Math.abs(obj.y-arr[i].y)<obj.height+dis){
                setPosition(obj);
                return;
            }
        }
    }
}
//检测是否重合
function test(obj:Sprite):void
{
    for(var i:int = 0;i<len;i++){
        if(obj != arr[i]){
            if(obj.hitTestObject(arr[i])){
                trace(obj.name,arr[i].name);
            }
        }
    }
}

 

------------------------------------------------------------------ Always put yourself in the other's shoes.If you feel that it hurts you,it probably hurts others,too.------------------------------------------------------------------
posted on 2015-11-24 11:50  晏过留痕  阅读(757)  评论(0编辑  收藏  举报