While viewing a post on bytearray.org and after teaching a class on creative technology at the avans hogeschool today, I got inspired to write some easy code to be informed by the timeline of a Movieclip when a certain label is reached.
A student of mine slapped me in the face with my own words that “code on the timeline is evil” when he asked how he could trigger an action inside the flash Document Class from the timeline or from a specific framelabel. My reply was simple: just call a method on a certain keyframe that you have exposed in the Document class. < Sssslappppp >
So I decided to show him the clean way by listening to an Event.ENTER_FRAME Event and checking the framelabel or the end of the timeline whenever the event handler got called. All from inside the Document class, no code on the timeline there.
I encapsulated the whole thing in a class, have it dispatch events you can register to and make it able to get some data out of it and at the same time make it work for different scenes (as he was working with them). In this way we can perfectly seperate design and timeline stuff from code, optimizing workflow by having designers tweak their animations and killer design while only informing the developer of some framelabels and eliminating spaghetti code and potential bugs.
For this purpose I wrote the TimelineListener class in the nl.dpdk.utils package. read on for some simple code.
//Document class ListenDemo with multiple scenes, multiple lables public function ListenDemo() { //create a new instance with a reference to the timeline we want to 'listen' to. var t : TimelineListener = new TimelineListener(this); //inform us when a new label is reached t.addEventListener(TimelineEvent.NEW_LABEL, onLabel); //inform when a new scene is reached t.addEventListener(TimelineEvent.NEW_SCENE, onScene); //inform whenever the end of a scene is reached (fires only once when staying on the last frame) t.addEventListener(TimelineEvent.TIMELINE_END, onEnd); } private function onLabel(event : TimelineEvent) : void { trace("new label reached: " + event.getLabel() + ", on frame: " + event.getFrame() + " in scene: " + event.getScene().name + " in the movieclip: " + event.getTimeline()); } private function onEnd(event : TimelineEvent) : void { event.target.destroy(); } private function onScene(event : TimelineEvent) : void { //do some scene changing stuff here }
I never meant to slap you in the face with your own words - sorry, hehe!
Thanks for publishing this nifty little piece of code, Roel.
Oh and thanks - ofcourse - for teaching us programming-newbies some Actionscript!
-Michiel (the guy behind the click-the-virus-to-kill-it-game)
Dit is echt een erg interessante post