Search code examples
actionscript-3timer

How to Increase a timer AS3


Hey everyone cant really figure out the easiest approach to this problem.

Basically I have a timer that starts in the beginning of the game like so:

//Create new timer object
        tEggTimer = new Timer (nTimerSpeed);
        //Listen for timer intervals
        tEggTimer.addEventListener(TimerEvent.TIMER, addEggs, false, 0, true);
        //start timer
        tEggTimer.start();

The nTimerSpeed is equal to (800);

Then I add the eggs like so:

private function addEggs(e:TimerEvent):void 
    {
        //var eggGlobalPosition:Point = _Egg.localToGlobal(new Point(_Bunny.x, _Bunny.y));

        _Egg = new mcEgg();
        stage.addChild(_Egg);
        _Egg.x = _Bunny.x;
        _Egg.y = _Bunny.y + 30;
        aEggArray.push(_Egg);
        trace(aEggArray.length);

    }

So in another enter frame function I want to change the value of the timer to (500), but whenever I try like so:

tEggTimer = new Timer (500);

tEggTimer.start();

like So:

private function updateDifficulty():void 
    {
        if (difficultyUpdate) return;

        if (nScore >= 2)
        { 
            tEggTimer.removeEventListener(TimerEvent.TIMER, addEggs);
            tEggTimer.stop();
            tEggTimer = new Timer(200);
            tEggTimer.addEventListener(TimerEvent.TIMER, addEggs);
            tEggTimer.start();

But this doesnt do anything but stop the timer entirely.

What can I do in order to decrease the timer correctly?

Thanks guys.


Solution

  • If you just want to change the timer speed, while keeping everything else the same, you could just change the delay property in the timer object.

    Sample here:

    import flash.utils.getTimer;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.events.MouseEvent;
    
    var speeds:Vector.<int> = new <int>[1000, 2000, 5000];
    var currentSpeed:int = 0;
    
    var timer:Timer = new Timer(speeds[currentSpeed]);
    function timerTick(inputEvent:TimerEvent):void {
        trace("Timer ticking: "+ getTimer());
    }
    timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true);
    timer.start();
    
    
    function clickedStage(inputEvent:MouseEvent):void {
        currentSpeed = ++currentSpeed % speeds.length;
        timer.delay = speeds[currentSpeed];
        trace("Timer delay set to "+ timer.delay);
    }
    this.stage.addEventListener(MouseEvent.CLICK, clickedStage, false, 0, true);
    

    Clicking on the stage will change the timer delay from 1 second, 2 seconds, 5 seconds and cycle. I'm just using getTimer() to show the rate of which the timer is ticking.

    Note that it seems from the output, every time the value is changed, the timer will automatically restart.