0
votes

Alright, so I am fairly new to AS3 and I have a level in my game where you have to stay alive for 45 seconds. If I use a code like (Or if there is a better code, I'll use that one)

   var myTimer:Timer = new Timer(1000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
myTimer.start();

function runOnce(event:TimerEvent):void {
trace("runOnce() called @ " + getTimer() + " ms");
}

How can I use this to make my game move to scene 6 if they stay alive for 45 seconds? I also want to display text on the animation that keeps track of how long they've been alive so they know how long they have left. How could I accomplish this?

2

2 Answers

0
votes
private var startTime:int;
function startGame() {
    // this is called when your game starts
    startTime=getTimer();
    ... // rest of init code
} 
function onEnterFrame(e:Event):void {
    // main loop, whatever you need to do in here
    currentTime=getTimer()-startTime; // here we receive the elapsed time
    // pause handling is excluded from this example!!11
    if (weAreDead()) {
        survivalTime= currentTime;// here
        ...
    } else if (currentTime>45000) { 
        //advance to scene 6 here
    }
}

Set the listener for Event.ENTER_FRAME to onEnterFrame, start the game with setting the stored time, and pwn.

0
votes

The simplest solution is to go ahead and use the timer, but set the value to 45000 and make sure to keep a reference of the timer or it will be garbage collected. Also, create a separate function which allows you to kill the timer from anywhere if this particular thing ever needs to just "go away" without completing.

public static const DELAY:int = 45;
private var _timer:Timer;

public function setTimer():void
{
    _timer = new Timer( DELAY * 1000, 1 );
    _timer.addEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
    _timer.start();
}

private function timerCompleteHandler( event:TimerEvent ):void
{
    disposeTimer();
    goDoTheThingThatYouNeededToDo();
}

public function disposeTimer():void
{
    _timer.stop();
    _timer.removeEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
    _timer = null;
}