Reputation:
I'm trying to make a ship game and I'm having an problem to get opponents fading as well.
Well, these opponents (like ships) has an class. In this class I do a interval to make its children fly to left (changing X per velocity number choosen on fourth argument in the function for adding enemies (addOpponent(opponentX, opponentY, opponentType, opponentVelocity)
) and, when any of them has coordinate X smaller than -25, must be removed, through class block of itself.
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;
}
}
}
}
}
I'm using this.parent.removeChild(this)
. I'm getting a error when the opponent X is smaller than -25, and it's on that time I want to remove the opponent child.
Upvotes: 2
Views: 45
Reputation: 14406
Here is how I would refactor this: (see code comments)
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;
}
}
}
}
Upvotes: 1