【问题标题】:Randomising array coordinates with no duplicates AS3无重复的随机数组坐标 AS3
【发布时间】:2016-03-19 01:48:40
【问题描述】:

对这种事情很陌生,所以请多多包涵。

所以基本上我有 4 个按钮,我使用“操作”面板将它们放到了舞台上。它们都设置了坐标,所以每次我运行游戏时,它们都在同一个地方。

现在这是我的问题,我希望这些按钮使用这些坐标随机化它们的位置,但我经常得到重复,这意味着一个按钮位于另一个按钮之上。

这是我目前的代码

var coordArray : Array = [
              new Point(44,420),
              new Point(270,420),
              new Point(44,550),
              new Point(270,550),

              ];            

var pointRange:Number = 4;
var randomPoint:int = Math.random()*pointRange;
answerButtons.x = coordArray[randomPoint].x;
answerButtons.y = coordArray[randomPoint].y;    

var pointRange_2:Number = 4;
var randomPoint_2:int = Math.random()*pointRange_2;
answerButtons_2.x = coordArray[randomPoint_2].x;
answerButtons_2.y = coordArray[randomPoint_2].y;

var pointRange_3:Number = 4;
var randomPoint_3:int = Math.random()*pointRange_3;
answerButtons_3.x = coordArray[randomPoint_3].x;
answerButtons_3.y = coordArray[randomPoint_3].y;

var pointRange_4:Number = 4;
var randomPoint_4:int = Math.random()*pointRange_4;
answerButtons_4.x = coordArray[randomPoint_4].x;
answerButtons_4.y = coordArray[randomPoint_4].y;

我已经在 Google 上大量搜索了这个问题,并且不断得到与 splice 和 shift 方法有关的答案。这是我需要的东西吗?我假设我需要一个函数在使用后从数组中删除一个点。

干杯。

【问题讨论】:

  • 您忘记在每次选择一个时从数组中删除所选项目...

标签: actionscript-3 flash random duplicates coordinates


【解决方案1】:

当你使用splice随机选择时,只需从列表中删除坐标:

var coordinates:Vector.<Point> = new <Point>[
    new Point(44, 420),
    new Point(270, 420),
    new Point(44, 550),
    new Point(270, 550)
];

function positionAtRandomCoordinate(object:DisplayObject):void {
    var index:int = Math.random() * coordinates.length;
    var coordinate:Point = coordinates.splice(index, 1)[0];
    object.x = coordinate.x;
    object.y = coordinate.y;
}

positionAtRandomCoordinate(answerButtons);
positionAtRandomCoordinate(answerButtons_2);
positionAtRandomCoordinate(answerButtons_3);
positionAtRandomCoordinate(answerButtons_4);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-12
    • 2018-04-24
    • 2012-08-26
    • 1970-01-01
    • 2021-06-24
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多