package { //imports import flash.display.DisplayObject; import flash.display.MovieClip; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.utils.getDefinitionByName; import flash.text.TextField; /** * Preloader class * @author Richard Parnaby-King */ public class Preloader extends MovieClip { //properties private var preloadText:TextField = new TextField(); /** * Add event listeners and add textfield to the stage */ public function Preloader() { if (stage) { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; } addEventListener(Event.ENTER_FRAME, checkFrame); loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress); loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError); addChild(preloadText); preloadText.x = (stage.stageWidth / 2) - (this.width / 2); preloadText.y = (stage.stageHeight / 2) - (this.height / 2); } /** * In the event of a loading error. * @param IOErrorEvent e */ private function ioError(e:IOErrorEvent):void { trace(e.text); } /** * Update the loading message * @param ProgressEvent e */ private function progress(e:ProgressEvent):void { preloadText.text = "Loading: " + Math.floor((loaderInfo.bytesLoaded / loaderInfo.bytesTotal) * 100) + "%"; } /** * Check if application has finished loading * @param Event e */ private function checkFrame(e:Event):void { if (currentFrame == totalFrames) { stop(); loadingFinished(); } } /** * Preloading has finished. Time to do some clean up. * Remove event listeners, remove objects from stage. */ private function loadingFinished():void { removeEventListener(Event.ENTER_FRAME, checkFrame); loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress); loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError); removeChild(preloadText); startup(); } /** * Call our main class so we can continue. */ private function startup():void { var mainClass:Class = getDefinitionByName("Main") as Class; addChild(new mainClass() as DisplayObject); } } }