actionscript-3 - 如何在不重复的情况下在数组中生成对象?
问题描述
我有 MC rockThrowers
被添加到舞台的 3 个不同位置。它们使用运行良好的随机生成器随机生成。用户单击舞台上的一个按钮,然后将其添加到rockThrowers
舞台并推入他们自己的数组aRockThrowerArray
中rockThrowers
在空位上添加一个新的。我尝试了不同的策略,主要是布尔值,并将它们从他们自己的类调用到我的主类,但似乎没有任何效果。这是我的
rockThrowers 类:
private function startPosition():void
{
// y position
this.y = (stage.stageHeight / 2) + 200;
//Start Speed
nSpeed = randomNumber(5, 8);
leftScreenSpawn = randomNumber(1, 3);
//For Left Screen
leftNeg = (stage.stageWidth / 2) - 200;
leftMiddle = (stage.stageWidth / 2) - 150;
leftPos = (stage.stageWidth / 2) - 100;
//Left Screen
if (leftScreenSpawn == 1)
{
this.x = leftNeg;
bLeftNeg = true; // Now if the left Rock thrower is destroyed then turn back to false on main engine class
}else
if (leftScreenSpawn == 2)
{
this.x = leftMiddle;
bLeftMiddle = true;
}else
if (leftScreenSpawn == 3)
{
this.x = leftPos;
bLeftPos = true;
}
//Move
startMoving();
}
现在在我的主类中,当用户单击左屏幕 Btn 时,我已经设置了这样的设置:
private function rockThrowerSpawn(e:MouseEvent):void
{
//Instantiate screens before hand
rockThrowerSpawnScreen.x = (stage.stageWidth / 2);
rockThrowerSpawnScreen.y = (stage.stageHeight / 2) + 200;
addChild(rockThrowerSpawnScreen);
rockThrowerSpawnScreen.left.addEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);
}
然后是 Spawn 函数:
private function chooseSpawnSideRockThrowers(e:MouseEvent):void
{
if (e.currentTarget == rockThrowerSpawnScreen.left) // Spawn LEFT
{
//add new rock thrower
rockThrowers = new mcRockThrowers();
//Add object
addChild(rockThrowers);
//Add to Array
aRockThrowerArray.push(rockThrowers);
//trace("LEFT SPAWN");
}
//Subtract resources and update text
nResources -= 10;
updateResourceTextField();
//Remove Listeners
rockThrowerSpawnScreen.left.removeEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);
rockThrowerSpawnScreen.destroy();
}
我知道仅此一项总是会产生随机位置我删除了所有不起作用的东西现在我回到了这个正方形。关于我如何做到这一点的任何想法?感谢所有支持。
解决方案
简单的。您需要一个以随机顺序生成 3 个值的有限数组。
var L:Array =
[
(stage.stageWidth / 2) - 200,
(stage.stageWidth / 2) - 150,
(stage.stageWidth / 2) - 100,
];
function fetchPosition():Number
{
// Get a random index based on the current length of L.
var anIndex:int = Math.random() * L.length;
// Record the result.
var result:Number = L[anIndex];
// Remove the result from the list.
L.splice(anIndex, 1);
return result;
}
因此,您可以在每次应用程序运行时有效地调用fetchPosition()三次,并且每次运行L的内容都将以随机顺序获取,更重要的是,您不会两次获得相同的值,因为获取的值已从数据集。
推荐阅读
- typescript - 如何在打字稿中调用具有多种类型数组的地图函数
- javascript - 谷歌表格 - 优化在一定范围内创建笔记的功能(非常慢)
- php - 完整地址 $_SERVER["HTTP_REFERER"];
- machine-learning - 无论输入如何,我的 RandomForest 都会为 model.predict_proba() 返回完全相同的概率
- sql - Oracle SQL 数据库内存中 - 比较压缩大小
- python - asyncio:发生异常时如何对对象进行排队
- python - 使用 colab 从内存中读取 .csv 文件
- arrays - 在C中循环遍历二维字符数组的正确方法
- postgresql - 身份验证问题 (KRB5\GSS)
- python - 按值和大小的递增顺序对嵌套的数字列表进行排序