Search code examples
actionscript-3flashactionscriptcountdowntimer

Keyboard Event copping another event flash as3


Hellow again people.

continuing on making the score board, I have not come across a problem with my Keyboard Event. The reset and start keys works fine but the stop key doesn't stop it rather resets it. I think it might have something to do with me putting the stop command in the reset code as well but I'm not sure how to go around it.

they all work perfect as (btn) but that's no good for me as the monitor will be far away. take a look?

stage.addEventListener( KeyboardEvent.KEY_DOWN, KeysDown);

function KeysDown(event:KeyboardEvent) 

//reset the timer with (space)
{
if(event.keyCode == Keyboard.SPACE)
timer.stop();
timeRemaining = 300;
showTime.text = formatTimeRemaining();

// start the timer
if(event.keyCode == Keyboard.ENTER)
timer.start();

// stop the timer
if(event.keyCode == Keyboard.S)
timer.stop();
}

Solution

  • When writing if statements, the curly braces { } must surround the body of the statement (if the body is 1 line then the braces can be omitted).

    Always use the braces and you won't run into this problem again.

    stage.addEventListener( KeyboardEvent.KEY_DOWN, KeysDown);
    
    function KeysDown(event:KeyboardEvent) 
    {
        if(event.keyCode == Keyboard.SPACE)
        {
            timer.stop();
            timeRemaining = 300;
            showTime.text = formatTimeRemaining();
        }
    
        // start the timer
        else if(event.keyCode == Keyboard.ENTER)
        {
            timer.start();
        }
    
        // stop the timer
        else if(event.keyCode == Keyboard.S)
        {
            timer.stop();
        }
    }