I am working on a very simple game in Flash. I want to make all the animations framerate agnostic, so that I can change the framerate without affecting the flow and speed of the game.
I read somewhere that if you want to do that, you simply create a Timer object and attach an event listener to this timer.
What if I have many objects that have to listen to the same timer? See the code to understand what I am trying to do. At this stage nothing breaks, but the event does not fire.
Here is the Main class, the one that runs on swf execution:
public class Main extends MovieClip {
private static var _stage:Stage;
private static var _timer:Timer;
public function Main() {
trace("STARTING_GAME");
init();
}
private function init(){
var player:Player = new Player(100);
this.addChild(player);
_stage = this.stage
_timer = new Timer(30);
}
public static function get stage():Stage{
return _stage;
}
public static function get timer():Timer{
return _timer;
}
}
And here is the Player class, one of the objects that will be needing the Timer:
public class Player extends MovieClip {
private var playerHealth:int;
public function Player(_health:int=100) {
init(_health);
}
private function init(_health:int){
trace("creating player object");
playerHealth = _health;
addEventListeners();
trace(Main.timer); //this returns [object timer] - so it's supposed to work?
}
private function addEventListeners(){
Main.timer.addEventListener(TimerEvent.TIMER, ef_Repaint);
//this.addEventListener(Event.ENTER_FRAME, ef_Repaint);
}
private function ef_Repaint(e:Event):void{
trace("timer event firing");
}
}
Thanks in advance!
You should start the timer.
The Timer class documentation says:
Also note that using a timer is not really the best approach. It is better to continue using
Event.ENTER_FRAMEand only execute the code if the delay you want has been elapsed:Finally, if you use either approach, you should not be really listening to
TimerEvent.TIMERorTimerEvent.TIMERin every object separately. You should have your event handler inMainand loop on your objects there and ask them to update. Having multiple event listeners is not good for performance, and they may get called in an order that you don’t expect, and you may end up with bugs that you can’t understand.