Search code examples
actionscript-3timerflappy-bird-clone

Action Script 3.0 timer doesn't stop


I'm trying to make flappy birds in actionscript (just for practicing and fun). This is my first programming language and I'm still new to this.

So the problem starts here, I want to make the bird rotates (as the real flappy bird does) every 2 seconds when no button is pressed. But it turned out that the timer still activates after I pressed spacebar again which I think it is supposed to stop the last timer first before activating the new one.

If I press spacebar 2 times, the timer will activate twice. Without stopping the timer first.

Code :

stage.addEventListener (KeyboardEvent.KEY_DOWN, jump);

function jump(event: KeyboardEvent):void
{
var myTimer4:Timer = new Timer (2000)

    if(event.keyCode == 32)
        {bird.y=bird.y-40;
         bird.rotation=0;
            myTimer4.stop();
            myTimer4.start();
}


myTimer4.addEventListener(TimerEvent.TIMER, fall);

function fall (e:TimerEvent):void{

    bird.rotation=40;
    myTimer4.stop();

}

Solution

  • I think the problem might be you are creating a new instance of Timer every time the key is pressed and myTimer4 takes in a new reference. Try removing it outside the function scope like this:

    var myTimer4:Timer = new Timer (2000);
    
    function jump(event: KeyboardEvent):void
    {
    
    
        if(event.keyCode == 32)
            {bird.y=bird.y-40;
             bird.rotation=0;
                myTimer4.stop();
                myTimer4.start();
    }