我正在按照http://markbennison.com/actionscript/as3-space-shooter/2-coding-projectiles/
上有关动作脚本3 的教程进行操作我正在使用第2部分编码弹丸,我不知道为什么在每次按下Play时总是说“错误”
“ ArgumentError:错误#2025:提供的DisplayObject必须是调用方的子级。”
这里是试图在按下空格键时发射子弹的确切代码,还有更多如何解决参数错误的信息。
function addBullet(startX,startY):void {
//declare an object instance from the bullet Class
var b: Bullet = new Bullet();
//set the new bullet's x-y coordinates
b.x = startX;
b.y = startY;
//add the new bullet to the stage
stage.addChild(b);
//store the object in an array
bullets_arr.push(b);
}
function moveBullet():void {
//loop through all instances of the bullet
//loop from '0' to 'number_of_bullets'
for (var i: int = 0; i < bullets_arr.length; i++) {
//move the bullet
bullets_arr[i].x += bulletSpeed;
//if the bullet flies off the screen, remove it
if (bullets_arr[i].x > stage.stageWidth) {
//remove the bullet from the stage
stage.removeChild(bullets_arr[i]);
//remove the bullet from the array
bullets_arr.removeAt(i);
}
}
}
有人可以给我提示更改任何东西吗?
答案 0 :(得分:2)
该错误表示该行运行时:
stage.removeChild(bullets_arr[i]);
bullets_arr[i]
所引用的项目实际上不在舞台上。可能是因为它已从舞台中删除。
虽然这可能不是导致错误的确切原因,但这里的一个大问题是从当前正在迭代的数组中删除项目。
当您执行以下操作时:bullets_arr.removeAt(i);
,您正在更改bullets_arr
数组的大小。
在第一次迭代中,i
是0
。您的第一个项目符号是bullets_arr[0]
,第二个项目符号是bullets_arr[1]
,第三个项目符号是bullets_arr[2]
,依此类推。如果在第一个循环中,最终从数组中删除了该项目,则意味着索引具有移动,所以现在您的第二个项目符号是bullets_arr[0]
,但是在下一个循环中,i
会增加到1
,所以现在您实际上已经跳过了第二个项目符号,正在检查第三个项目,删除第一个项目符号后,现在位于索引1
。
在moveBullet
函数中,更改循环以使其向后迭代,这样,如果删除项目,它不会移动尚未迭代的索引。
for (var i: int = bullets_arr.length - 1; i >= 0; i--) {