Search code examples
actionscript-3actionscriptflash-cs3

Timer in Action Script 3


I have problem that I need to create timer but I want to pass on a variable to it, how to do it? Is it possible in AS3?

I tried like this:

            bonusPlayer1Timer = new Timer(5000);
            bonusPlayer1Timer.addEventListener(TimerEvent.TIMER, bonusChanges(player1));
            bonusPlayer1Timer.addEventListener(TimerEvent.TIMER_COMPLETE, bonusChangesRemove(player1));
            bonusPlayer1Timer.start();

function bonusChanges(event:TimerEvent, playerBonus:Player):void {
    switch (playerBonus.bonus) {
        case 0 :
            playerBonus.multipleShooting = false;
            playerBonus.bonus = -1;
            break;
...}}

But I have error:

1067: Implicit coercion of a value of type Player to an unrelated type flash.events:TimerEvent.
1136: Incorrect number of arguments.  Expected 2.

And this error is in the bold line.

Can I use it in this way? Or I have to create two the same function for every of my players because I am not allow to pass on any different arguments to the timer function?

Thank you,


Solution

  • Create a class that extends the Timer class and add a property for the Player.

    public class PlayerTimer extends Timer
    {
        public var thePlayer:Player;
    
        public function PlayerTimer(delay:Number, repeatCount:int=0)
        {
            super(delay, repeatCount);
        }       
    }
    

    Using your example the code would be something like this:

    bonusPlayer1Timer = new PlayerTimer(5000);
    bonusPlayer1Timer.thePlayer = new Player();
    bonusPlayer1Timer.addEventListener(TimerEvent.TIMER, bonusChanges);
    bonusPlayer1Timer.addEventListener(TimerEvent.TIMER_COMPLETE, bonusChangesRemove);
    bonusPlayer1Timer.start();
    
    function bonusChanges(event:TimerEvent):void {
        var playerBonus:Player = PlayerTimer(event.target).thePlayer; 
        switch (playerBonus.bonus) {
            case 0 :
                playerBonus.multipleShooting = false;
                playerBonus.bonus = -1;
                break;
    ...}}