Preloader (Flixel)

From Flash Game Dojo

Jump to: navigation, search
More Snippets

Preloaders in AS3 are a little bit messed up, so Flixel takes care of MOST of it for you. However, you need to make a new file and add some code to it to help flixel finish the job. The class we need to create should be called, for the sake of simplicity,, and reside in your normal source folder. Paste or edit the file to look like this:

        import org.flixel.system.*;
	public class Preloader extends FlxPreloader
		public function Preloader():void
			className = "HelloWorld";

HelloWorld must be spelled and capitalized exactly the way your main class is spelled and capitalized. If your main class is, then FlxPreloader.className should be set to "HelloGlobe". Finally, underneath the size macro ([SWF(width= etc) in your main class, add this line of code:

[Frame(factoryClass="Preloader")] //Tells Flixel to use the default preloader 

Now your project will automatically display the default Flixel preloader each time it loads.

Custom Preloader

In order to create a custom preloader, add these overrides after the constructor:

override protected function create():void {
	_buffer = new Sprite();
	//Add stuff to the buffer...
override protected function update(Percent:Number):void {
	//Update the graphics...

Be careful about referring to classes other than your preloader inside of it, as they will have to be loaded before the anything shows up. Normally this isn't really a problem, since most of your classes are probably FlxObjects which can't be used until after the game starts anyway, but if you're writing a preloader from scratch, it may pose a problem. Unfortunately, you can't get from your preloader to your Main class without some kind of reference to it. To avoid having a direct reference while still activating Main, flixel uses a String to refer to Main.

////from FlxPreloader
                    var mainClass:Class = Class(getDefinitionByName(className));
	                var app:Object = new mainClass();
	                addChild(app as DisplayObject);

If you do it this way, flash won't try to load the main class until after the preloader has loaded. If className doesn't refer to a valid class, it won't do anything after the preloader.

Another important thing to note is that preloaders generally extend the MovieClip class. When the .swf compiles, this MovieClip will be the only thing on the stage, and it will act as a wrapper for the whole game. The first thing it does is call stop(); to stop the game on the first frame, and the last thing it does is call nextFrame(); and add an instance of your Main class. All the logic between those will likely in pure ActionScript, using Events and such. Looking at FlxPreloader will give a good idea of one way to go about this.

See Also

Personal tools