导航问题

时间:2011-03-03 11:34:13

标签: actionscript-3 button random stage

我正在开发一个应用程序,我有一个导航问题。 我在舞台上有随机按钮,但有些重叠是不可避免的。 我想解决这个问题,但我不知道如何解决。 有没有人有任何想法可以帮助我?

AS3

for (var i:int=0; i<16; i++){
var mc_sq:MovieClip = new mc_square();
mc_sq.y = Math.round(Math.random()* 200);
mc_sq.x = Math.round(Math.random()* 300);
mc_sq.buttonMode = true;
addChild(mc_sq);
}

2 个答案:

答案 0 :(得分:0)

以下代码已经过测试并正常工作

var items:Array = [];

var numItems:Number = 16;

for(var i:int; i < numItems; i++) {
    var mc:Mc = new mc_square();
    mc.buttonMode = true;
    addChild(mc);

    while(!freezone(mc)) {
        mc.x = Math.random() * 200;
        mc.y = Math.random() * 300;     
    }
    items.push(mc);
}

function freezone(mc:MovieClip):Boolean {
    var hit:Boolean = false;
    items.forEach(function(item:MovieClip, i:int, a:Array):void {
        if(mc.hitTestObject(item)) {
            hit = true;
        }
    });
    return !hit;
}

答案 1 :(得分:0)

简单的命中测试将是一个简单的解决方案,但如果有许多按钮并且这些按钮的空间有限,则可能会让您遇到问题。根据具体情况,更好(也更复杂)的解决方案可能是栅格化空间并将按钮放入(几乎)每个单元格中随机移动:

// environment variables
const numButtons:int = 16;
const maxButtonWidth:int = DummyButton.MAX_WIDTH;
const maxButtonHeight:int = DummyButton.MAX_HEIGHT;
const width:Number = stage.stageWidth;
const height:Number = stage.stageHeight;
// pseudo-random positioning
// ratio is needed for a proportional grid
var areaRatio:Number = width / height;
var maxButtonRatio:Number = maxButtonWidth / maxButtonHeight;
// compute buttons per column and row (take aspect ratios into account)
var cols:int = Math.floor(Math.sqrt(numButtons) * (areaRatio / maxButtonRatio));
var rows:int = Math.ceil(numButtons / cols);
// available space for each button within a grid segment
var spaceX:Number = (width - maxButtonWidth * cols) / cols;
var spaceY:Number = (height - maxButtonHeight * rows) / rows;
// throw an error if buttons won't fit (based on maximum dimensions)
if (cols < 1 || rows < 1 || spaceX < 0 || spaceY < 0) {
    throw new Error("buttons do not fit into area");
}
// for every button
for (var i:int = 0; i < numButtons; i++) {
    var row:int = Math.floor(i / cols);
    var col:int = i % cols;
    var button:Sprite = new DummyButton();
    // coordinate = grid segment + random shift
    button.x = col * (maxButtonWidth + spaceX) + Math.random() * spaceX;
    button.y = row * (maxButtonHeight + spaceY) + Math.random() * spaceY;
    stage.addChild(button);
}