我的Flash游戏有点问题。每当他们到达时我的一系列鸟类(障碍物)让我们说x-800他们每次在阵列中的随机位置重生在起始位置并且效果很好。 但 每次循环时,鸟一对一地堆叠在一个阵列的第一个位置。这很奇怪。
public function setUpBirds() {
for (var i:int = 0 ;i< 10; i++) {
var mcClip:Bird = new Bird();
var yVal:Number = (Math.ceil(Math.random()*100));
birds.push(mcClip);
birds[i].x = 100 * i;
birds[i].y = yVal * i;
birdsContainer.addChild(mcClip);
}
}
private function moveBirds(event:Event):void {
birdsContainer.x = birdsContainer.x -10;
if (birdsContainer.x == -500) {
birdsContainer.x = 500;
setUpBirds();
}
}
有什么想法吗?
答案 0 :(得分:0)
每当birdsContainer
x
500
setUpBirds()
时,您拨打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
第一次,一切都很棒,你的 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);
}
数组现在有10个项目。
现在,第二次运行该函数:
birds
现在你看到了问题?您的mcClip
数组现在有20个项目,因此您现在引用数组中的错误项目。
要解决此问题,只需在birds[birds.length-1].x = 100 * i
var而不是数组上设置x / y,或者 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
这样,你只创造了10只鸟,而你只是在每个循环中重置那些鸟的{{1}}位置。