每当您的birdsContainer 有一个x 或500 时,您就调用setUpBirds(),所以让我们一步一步来看看发生了什么:(用注入到您的代码中的代码cmets 来解释)
setUpBirds 第一次运行:
for (var i:int = 0 ;i< 10; i++) {
//a new bird is created 10 times
var mcClip:Bird = new Bird();
var yVal:Number = (Math.ceil(Math.random()*100));
//you add it to the array
birds.push(mcClip);
//birds[1] properly refers to the item you just pushed into the array
birds[i].x = 100 * i;
birds[i].y = yVal * i;
birdsContainer.addChild(mcClip);
}
第一次通过,一切都很好,您的 birds 数组现在有 10 个项目。
现在,函数第二次运行:
for (var i:int = 0 ;i< 10; i++) {
//create 10 more new birds (in addition to the last ones)
var mcClip:Bird = new Bird();
var yVal:Number = (Math.ceil(Math.random()*100));
//add to the array (which already has 10 items in it)
birds.push(mcClip); //so if i is 5, the item you just pushed is at birds[14]
//birds[i] will refer to a bird you created the first time through
//eg bird[0] - bird[9] depending on `i`, but really you want bird[10] = bird[19] this time around
birds[i].x = 100 * i; //your moving the wrong bird
birds[i].y = yVal * i;
//the new birds you create, will have an x/y of 0
//since birds[i] doesn't refer to these new birds
birdsContainer.addChild(mcClip);
}
现在你看到问题了吗?您的 birds 数组现在有 20 个项目,因此您现在引用了数组中的错误项目。
要解决此问题,只需在 mcClip var 而不是数组上设置 x/y,或者执行 birds[birds.length-1].x = 100 * i 以使用添加到数组中的最后一项。
顺便说一句,你的表现会变得很糟糕,很快就会一直创造 10 只新鸽子。如果你不断地创造新的,你需要摆脱那些老鸟。
似乎您可能想要做的只是在每个循环中重新定位现有的鸟类,所以看起来像这样:
for (var i:int = 0 ;i< 10; i++) {
//check if there is NOT a bird already at this position in the array
if(birds.length <= i || !birds[i]){
//no bird yet, so create it and add it and push it
var mcClip:Bird = new Bird();
birds.push(mcClip);
birdsContainer.addChild(mcClip);
}
//now set the position of the bird
var yVal:Number = (Math.ceil(Math.random()*100));
birds[i].x = 100 * i;
birds[i].y = yVal * i;
}
这样,您只创建了 10 只鸟,并且您只是在每个循环中重置这些鸟的 y 位置。