我正在尝试制作一款船游戏,但我遇到了让对手褪色的问题。
嗯,这些对手(如船只)有一个班级。在这个课程中,我做了一个间隔,让它的孩子飞到左边(在每个速度数字上改变X选择添加敌人的函数中的第四个参数( addOpponent(opponentX, opponentY, opponentType, opponentVelocity)
),当他们中的任何一个坐标X小于-25,必须通过 class 块自行删除。
package {
import flash.display.*
import flash.display.MovieClip;
import flash.utils.setTimeout;
import flash.utils.setInterval;
import flash.utils.clearInterval;
public class opponentNave extends MovieClip {
public function opponentNave(opponentVelocitySet) {
var loopMoveClassicOpponentsNave:uint = setInterval(movingClassicOpponentNave, 58);
function movingClassicOpponentNave() {
if (x < -25) {
clearInterval(loopMoveClassicOpponentsNave);
this.parent.removeChild(this);
} else {
x -= opponentVelocitySet;
}
}
}
}
}
我正在使用this.parent.removeChild(this)
。当对手X小于-25时我得到一个错误,而那时我想要移除对手的孩子。
答案 0 :(得分:2)
以下是我将如何重构:(参见代码注释)
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class opponentNave extends MovieClip
{
//create a class scoped variable for the velocity
private var velocitySet:Number;
public function opponentNave(opponentVelocitySet)
{
//set the velocity var
velocitySet = opponentVelocitySet;
//wait for this object (opponentNave) to be added to the display before doing anything display oriented
this.addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true);
}
private function addedToStage(e:Event):void {
//run a function every frame tick of the application's fps
//this is best for things that are display oriented instead of time based ways like Timer or Intervals
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(e:Event):void
{
if (x < -25){
if (this.parent) this.parent.removeChild(this);
this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
else
{
x -= velocitySet;
}
}
}
}