AS3 Using multiple timer to show / hide enemies
i have a shooting game that works with some sort of rounds, for instance, this round is gonna show 4 e开发者_如何学JAVAnemies on the screen that the user has to shoot. I show the 4 enemies at a half seconds interval of each one so it doesnt all appear on the same time. Using something like:
enemiesShowTimer = new Timer(0.5 * 1000, 1);
enemiesShowTimer.addEventListener(TimerEvent.TIMER, showEnemyAtTime);
enemiesShowTimer.start();
The player has 2 seconds to kill each enemy after they appear, so i also use this:
enemiesCleanTimer = new Timer(roundConfig.getSecondsPerEnemy() * 1000, 1);
enemiesCleanTimer.addEventListener(TimerEvent.TIMER, cleanEnemies);
enemiesCleanTimer.start();
The problem is, after the player dies i change scene and if i still have like 3 alive, enemies, the threads will try to run the methods and it will crash. I'm using always the same variable to the start the timer whenever i need it. How can i solve this? Will i have to store each "thread" (timer) on a list and then stop each one separately? Because the way it is, the other threads are in some sort of "limbo" and i cant stop then, just the last one.
Any helps?
Thank you!
First, really quickly, I'll just say that there are no threads here, AS3 does not have any multi-threading. So let's avoid using that word as it has very specific meaning. This is not it, and using it will lead to confusion.
Now for your problem, yes you will need to stop each timer when you are done with them. So you will need to keep a reference to each one and then call stop or reset when you are switching your scenes. A simple way is to store them all in an array and just loop over it when you need to stop them.
Hopefully that helps, let me know if you have any further questions.
Typically in a game situation, to avoid multiple timers (and the overhead/performance hit of running them), there would be a single timer that runs continuously (as long as the game is active), called something like GameLoop and objects will register/deregister with that as needed.
Incidentally, this also provides a simple way to pause a game.
I'm sure there's a good reason for this, but if you overwrite a Timer instance in AS3, the previous timer will continue to run indefinitely with no way to stop it (as its pointer will have been overwritten). So you'll want to stop any timers before you overwrite them, as Tyler mentioned.
精彩评论