所以,我有这个带有以下代码的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()
你知道我错过了什么吗?这绝对是一个范围问题,所以我需要包括什么才能让整个班级认出炸弹?
答案 0 :(得分:1)
bomb
不属于MainClass.container
。 bomb
是独生子女。
参考以下代码。
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;
*/
}