0
votes

I'm trying to create a game over screen for my space ship game, when player's shields reach 0 it goes to game over screen and stop the gameplay. The game over screen is working, but I can't stop the gameplay. I tried to set the Ship to null when player's shields reach 0 but I got error 1009. And all the gameplay objects (Ship, Enemy...) will loaded to the stage when "public function fGameStart(evt: Event): void {" executes, is there a way that I can stop this function from running when game over? Any help is greatly appreciated!

public class Engine extends MovieClip {
    private var preloader: ThePreloader;

    public function Engine() {
        stage.addEventListener("gameSTART", fGameStart);
        stage.addEventListener("gameOVER", fGameOver);
    }

    private var numStars: int = 80;
    public static var enemyList: Array = new Array();
    private var ourShip: Ship;

    public function fGameStart(evt: Event): void {

        ourShip = new Ship(stage);
        ourShip.x = stage.stageWidth / 2;
        ourShip.y = stage.stageHeight / 2;
        ourShip.addEventListener("hit", shipHit, false, 0, true);
        stage.addChild(ourShip);

        for (var i: int = 0; i < numStars; i++) {
            stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
        }

        addEventListener(Event.ENTER_FRAME, loop, false, 0, true);

        function loop(e: Event): void {

            if (Math.floor(Math.random() * 20) == 5) {
                var enemy: Stinger = new Stinger(stage, ourShip);
                enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy);
                stage.addChild(enemy);
            }

            else if (Math.floor(Math.random() * 80) == 5) {
                var enemy2: Stinger2 = new Stinger2(stage, ourShip);
                enemy2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy2.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy2);
                stage.addChild(enemy2);
            }
        }
    }

    public function fGameOver(e: Event) {
        gotoAndStop(4);
        ourShip = null;
    }


}
1

1 Answers

0
votes

There is no point setting the ourShip variable to null. It will not remove the DisplayObject from the stage, or remove it from memory. In fact the very reason you get this error is you setting it to null.

What you need to do is stop the loop function from triggering.

public function fGameOver(e: Event) {
    gotoAndStop(4);
    //ourShip = null;
    stage.removeChild(ourShip);
    removeEventListener(Event.ENTER_FRAME, loop);
}

also setting a weak reference for you listener might be a bad idea here

//addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
//why not:
addEventListener(Event.ENTER_FRAME, loop);