Hey guys,
I just tried to create a custom preloader, it’s not fancy, but this worked:
package;
import openfl.display.Sprite;
import openfl.events.Event;
@:keep class Preloader extends Sprite {
private var progress:Sprite;
public function new () {
super ();
progress = new Sprite ();
progress.graphics.beginFill (0xFF0000);
progress.graphics.drawRect (0, 0, 100, 100);
addChild (progress);
progress.scaleX = 0;
}
public function onInit ():Void {
trace ("init");
}
public function onLoaded ():Void {
trace ("loaded");
var delay = 60;
addEventListener (Event.ENTER_FRAME, function (_) {
delay--;
if (delay == 0) {
trace ("delayed start");
dispatchEvent (new Event (Event.COMPLETE));
}
});
}
public function onUpdate (bytesLoaded:Int, bytesTotal:Int):Void {
trace ("update: " + bytesLoaded + "/" + bytesTotal);
if (bytesTotal == 0) {
progress.scaleX = 0;
} else {
progress.scaleX = bytesLoaded / bytesTotal;
}
}
}
FYI, currently OpenFL will skip the preloader on native builds, and will skip on Flash or HTML5 if it is already before it would initialize a preloader. We could possibly change this if there’s important logic in the custom preloaders, let me know.
I used <app preloader="Preloader" />
and tested on HTML5 to see the above work
I’m also open to ideas if you think the system can be improved, perhaps it should be something related to LoaderInfo? For example:
class Preloader extends Sprite {
public function new (loaderInfo:LoaderInfo) {
super ();
loaderInfo.addEventListener (Event.COMPLETE, loaderInfo_onComplete);
loaderInfo.addEventListener (ProgressEvent.PROGRESS, loaderInfo_onProgress);
}
...
private function loaderInfo_onComplete (event:Event):Void {
dispatchEvent (event);
}
}
Or perhaps (even better) have the loaderInfo
set already, and don’t pass it in
class Preloader extends Sprite {
public function new () {
super ();
loaderInfo.addEventListener (Event.COMPLETE, loaderInfo_onComplete);
loaderInfo.addEventListener (ProgressEvent.PROGRESS, loaderInfo_onProgress);
}
...
private function loaderInfo_onComplete (event:Event):Void {
dispatchEvent (event);
}
}
What do you think?