OpenFL custom preloader

Recent problem with the preloader in my games inspired me to write this small tutorial on how to make a custom OpenFL preloader.

My version works great with the current OpenFL 9.1.0 and Lime 7.9.0, so feel free to use it as you want.

The first thing you need to do is to add a new Preloader class.
Then refer to this class in your project.xml file:

<app ... preloader="path.to.Preloader" />

Here is the part of the code to add the background image. You can have different backgrounds for different targets:

#if flash
@:bitmap("assets/preload_flash.jpg") class Back extends BitmapData {}
#elseif html5
@:bitmap("assets/preload_html5.jpg") class Back extends BitmapData {}
#elseif android
@:bitmap("assets/preload_andy.jpg") class Back extends BitmapData {}
#elseif ios
@:bitmap("assets/preload_ios.jpg") class Back extends BitmapData {}
#else
@:bitmap("assets/preload_default.jpg") class Back extends BitmapData {}
#end
 
...
 
class Preloader extends Sprite
{
	private var _back:Bitmap = null;
 
	public function new()
	{
		super();
 
		//get screen width and height to resize our bitmap, if game screen size is bigger or smaller
		var w:Int = Lib.current.stage.stageWidth;
		var h:Int = Lib.current.stage.stageHeight;
 
		var bmpd:BitmapData = new Back(w, h);
		_back = new Bitmap(bmpd, PixelSnapping.AUTO, true);
#if !html5 //not working in HTML5 since OpenFL 7, so fix it in onUpdate
		_back.width = w;
		_back.height = h;
#end
		addChild(_back);
 
...
 
#if (flash || html5) //progress is not working for native anyway
		addEventListener(ProgressEvent.PROGRESS, onUpdate);
#end
		addEventListener(Event.COMPLETE, onLoaded);
	}

Since this bitmap loads differently for the HTML5 target, you need to fix its width/height at the onUpdate function:

	private function onUpdate(pe:ProgressEvent):Void
	{
		if(pe.bytesTotal > 0)
		{
			var percentLoaded:Float = pe.bytesLoaded / pe.bytesTotal;
 
...
 
#if html5
			if(_back.width != 0) //fix background image size for HTML5
			{
				_back.width = Lib.current.stage.stageWidth;
				_back.height = Lib.current.stage.stageHeight;
			}
#end
		}
	}

If you don’t want your game to start automatically after it is loaded (site-lock check, for example), you can do the following on Event.COMPLETE:

	private function onLoaded(e:Event):Void
	{
		e.preventDefault(); //prevent game to start automatically, we start it later with Event.UNLOAD
 
		if(...) //everything is fine
			dispatchEvent(new Event(Event.UNLOAD)); //start the game
	}

That’s it!
I updated the CustomPreloader demo at the openfl-samples library on Github, but merging my pull request will most likely take some time, so you can get it from my Github page here: https://github.com/pozirk/openfl-samples/tree/master/features/display/CustomPreloader

Leave a Reply

DISCLAIMER: The content in this blog represents the opinion of the author. No information here should be used for any purpose except for entertainment.