AS3 - 正确引用MovieClip

时间:2012-08-15 16:09:26

标签: actionscript-3 scope movieclip

所以,我有这个带有以下代码的Player.as类文件:

private function PressAKey(event:KeyboardEvent):void
 {
   getDistance();
   if(event.keyCode == 32 && placedBomb == false && bombNumber == 0)//space
 {
   xKey = true;
   placeBomb();
   placedBomb = true;
}
}

将此与placeBomb()函数结合使用:

private function placeBomb():void{

 MainClass.container.addChildAt(bomb,0);
 bomb.x = this.x;
 bomb.y = this.y+20;
 bombNumber ++;
}

问题来自于这个试图计算玩家和炸弹之间距离的功能,以便我可以开始建立互动:

private function getDistance():void{
 distance = Math.sqrt( ( this.x - MainClass.container.bomb.x ) * ( this.x - MainClass.container.bomb.x ) + ( this.y - MainClass.container.bomb.y ) * ( this.y - MainClass.container.bomb.y ) );
 trace(distance);
}

我在尝试时遇到此错误:

TypeError: Error #1010: A term is undefined and has no properties.
at Player/getDistance()
at Player/PressAKey()

你知道我错过了什么吗?这绝对是一个范围问题,所以我需要包括什么才能让整个班级认出炸弹?

1 个答案:

答案 0 :(得分:1)

bomb不属于MainClass.containerbomb是独生子女。

参考以下代码。

private function getDistance():void
{
   var bomb:DisplayObject = MainClass.container.getChildAt(0);

   distance = Math.sqrt( ( this.x - bomb.x ) * ( this.x - bomb.x ) + ( this.y - bomb.y ) * ( this.y - bomb.y ) );
   trace(distance);
}

如何引用所有孩子。

for(var i:int = 0; i<parentObject.numChildren; i++)
{ 
   var object:DisplayObject = parentObject.getChildAt(i);
   /*
   p.s: if a child object type is MovieClip. must be typecasting.
   var object:MovieClip = parentObject.getChildAt(i) as MovieClip;
   */
}