简单的命中测试将是一个简单的解决方案,但如果有很多按钮并且这些按钮的空间有限,则可能会给您带来问题。根据具体情况,更好(也更复杂)的解决方案可能是对空间进行栅格化,并在(几乎)每个单元格中随机放置一个按钮:
// 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);
}