Let’s say you are playing a game that is keeping score. You are doing very well and you are close to beating someone else’s high score. All of sudden, you become distracted. The house is on fire! You want to save the house, but you also don’t want to lose the 30 minutes you’ve invested in to your game.
What do you do? Do you save the house or lose your best opportunity to top that high score?
You don’t even have to answer that question. Why? Because you can do BOTH.
First, pause the game, put out the fire, and when you are able to breathe clean air again, resume your game.
Let me show you one way this can be done.
1) Add an event listener for the keyboard.
stage.addEventListener(KeyboardEvent.KEY_DOWN,checkKeysDown);
2) Add a boolean variable to hold your pause (true or false) value.
private var _Paused:Boolean = false;
3) Add your checkKeysDown function.
function checkKeysDown(event:KeyboardEvent):void { if (event.keyCode == 119) //F8 function key { _Paused = true; } if (event.keyCode == 120) //F9 fnction key { _Paused = false; } }
4) In your function that is moving your game along (most likely your ENTER_FRAME event), place the following code at the beginning of the function.
if (_Paused == true) { var timePassed2:int = getTimer() - lastTime; lastTime += timePassed2; return; }
If the gamer hits F8, _Paused gets set to true. When the game enters your ENTER_FRAME function, you simply handle whatever code is necessary (like in my case – keeping my timer going), then simply call the return method. The code beyond this if statement will never execute again until the gamer presses F9 to change the value of the boolean, _Paused to false.