Home > Software design >  Countdown Timer in AS3
Countdown Timer in AS3

Time:06-14

I'm testing the opposite script as a countdown timer, and there's a type error:

TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@33d6b881f29 to flash.events.TimerEvent.

var goalTimerScore: int =  Math.floor(Math.random() * 101)   20;
var Minutes:Number = Math.floor(Math.random() * 11);
var Seconds:Number = Math.floor(Math.random() * 60);
timerMin_txt.text = String(Seconds);
timerSec_txt.text = String(Minutes);

timerWatch.addEventListener(Event.ENTER_FRAME, countTimer);
timerWatch.play();

function countTimer(e:TimerEvent):void {
    if (timerWatch.currentFrame == 61) {
        Seconds--;
        if (Seconds > 59) {
            Seconds = 0;
            timerSec_txt.text = "0"   Seconds;
            Minutes--;
            if (Minutes > 10) {
                timerMin_txt.text = ""   Minutes;
            } else {
                timerMin_txt.text = "0"   Minutes;
            }
            if (Minutes == 0 && Seconds == 0) {
                timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
                timer.stop();
                gotoAndPlay("gameover_Hidden3");
                return;
            }
        } 
        else {
            if (Seconds >= 10) {
                timerSec_txt.text = ""   Seconds;
            } else {
                timerSec_txt.text = "0"   Seconds;
            }
        }
    }
}

Any ideas how to solve this?

CodePudding user response:

You have the wrong function parameters, they should be:

function countTimer(e:Event):void {

As a suggestion, running a timer off the frame rate can be pretty inconsistent as it relies on a constant frame rate. Probably better to use a time based approach.

You can use the Timer class for a basic approach. There is an example in the asdocs of a count down.

https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html

CodePudding user response:

function countTimer(e: Event): void {
    if (timerWatch.currentFrame == 61) {
        Seconds--;
        if (Seconds < 0) {
            Minutes--;
            Seconds = 59;
        }

        if (Minutes == 0 && Seconds == 0) {
            timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
            timerWatch.stop();
            gotoAndPlay("gameover_Hidden3");
            return;
        }

        if (Minutes >= 1 && Seconds == 0) {
            if (Minutes == 0) {
                timerMin_txt.textColor = 0xFF0000;
                timerSec_txt.textColor = 0xFF0000;
            }
        }

    }
    if (Seconds < 10) {
        timerSec_txt.text = "0"   Seconds;
    } else {
        timerSec_txt.text = ""   Seconds;
    }
    if (Minutes < 10) {
        timerMin_txt.text = "0"   Minutes;
    } else {
        timerMin_txt.text = ""   Minutes;
    }
}
  • Related