以下是在街道上生成公民的课程。他们左右两边走,分配他们将面对的一面,他们移动的速度和他们的y位置。我以前在构造函数中使用了函数setUpCitizens(),但我想使用ADDED_TO_STAGE和REMOVED_FROM_STAGE,因为我在删除级别和监听器时遇到了问题。
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;
import flash.utils.Timer;
public class Citizen extends MovieClip
{
private var dx:Number;// speed and direction
private var lastTime:int;// animation time
public function Citizen(side:String, _speed:Number, yPos:Number)
{
var side = side;
var speed = _speed;
var yPos = yPos;
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void
{
setUpCitizens();
addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
private function onRemovedFromStage(event:Event):void
{
removeAllCitizens();
this.removeEventListener(Event.ENTER_FRAME,moveCitizen);
}
private function setUpCitizens():void
{
if (side == "left")
{
this.x = -40;// start to the left
dx = _speed;// walk left to right
this.scaleX = 1;// reverse
}
else if (side == "right")
{
this.x = 5720;// start to the right
dx = - _speed;// walk right to left
this.scaleX = -1;
}// not reverse
this.y = yPos;// vertical position
this.gotoAndStop(Math.floor(Math.random()*9+1));
// set up animation;
this.addEventListener(Event.ENTER_FRAME,moveCitizen);
lastTime = getTimer();
}
private function removeAllCitizens():void
{
removeEventListener(Event.ENTER_FRAME,moveCitizen);
parent.removeChild(this);
}
我收到了这个错误:
我这样叫这个班:
var c:Citizen = new Citizen(side,speed,yPos);
这是从父类对象Level1调用的。我也很难尝试引用所有生成的孩子并将它们全部移除以希望加速游戏......
感谢您的任何建议?
答案 0 :(得分:2)
在方法中创建变量时,它们只存在于该方法中。您的Citizen构造函数创建var speed,var size和var yPos,但只要该方法完成,这些变量就会丢失。您需要将它们存储在类属性中(例如您的dx和lastTime)。将类似于citizenSpeed:Number的内容添加到类属性中,然后在Citizen构造函数中,将传递的参数分配给该变量,即
public class Citizen extends MovieClip
{
private var dx:Number;// speed and direction
private var lastTime:int;// animation time
//added lines
private var citizenSpeed:Number;
private var citizenSide:String;
private var citizenYPos:Number;
public function Citizen(_side:String, _speed:Number, _yPos:Number)
{
citizenSide = _side;
citizenSpeed = _speed;
citizenYPos = _yPos;
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
...
然后,在setUpCitizens()中,只引用那些成员变量(citizenSpeed等)。
你得到的错误是因为setUpCitizens()包含引用它不知道的变量的代码,因为它们在那时已超出范围。
希望有所帮助!
乙