Wednesday, June 27, 2012

[Action Script] keyListener functions differently after first time on frame June,2012

A while ago I asked on these forums how to implement a pause feature in my game. It works great! However, I've just noticed that when you leave the frame (each frame of the main timeline holds the MCs for one level of the game) and return to it, pausing no longer works. I did some tracing to try and uncover what was happening, and it seems that anytime beyond my first "visit" to the frame, it fails to toggle isPaused = !isPaused and it executes pauseHUD == false AND pauseHUD == true. I've included the code (and omitted everything that is not relevant) below.

Code: onClipEvent (load) {

//Creates a listener for the Space Bar key and sets isPaused variable
var isPaused:Boolean = false;
var keyListener:Object = new Object();

//variable for pause sound and HUD
var pauseHUD = false;

//Loads the pause sound
pause_sound = new Sound();
pause_sound.attachSound("pause");

Key.addListener(keyListener);

keyListener.onKeyUp = function():Void
{
    if(Key.getCode() == Key.SPACE)
    {
        //toggle pause state
        isPaused = !isPaused;
                //start sound if not already playing
                if (pauseHUD == false) {

                        pause_sound.start();
                        pauseHUD = true;
                        trace("Executing A");
                        //code that shows HUD omitted

                } else if (pauseHUD == true) {

                        pauseHUD = false;
                        trace("Executing B");
                        //code that hides HUD omitted

                }
               
    }
}


function onEnterFrame():Void
{
       
 trace("isPaused = "+isPaused);
 trace("pauseHUD = "+pauseHUD);
       
    if(isPaused)
    {

    //code that pauses player and shows pause menu omitted
       
    }
    else
    {

    //code that unpauses player and hides pause menu omitted

    }
       
}In the interest of being thorough here's what I see in OUTPUT on my first visit to the frame when I press spacebar:

isPaused = false
pauseHUD = false
Executing A
isPaused = true
pauseHUD = true

And here's what I see on any subsequent visits when I press spacebar:

isPaused = false
pauseHUD = false
Executing A
Executing B
isPaused = false
pauseHUD = false

Any clue as to why this is and what I can do to prevent it from happening?
keyListener functions differently after first time on frame

Related Post



0 comments: