Saturday, December 21, 2013

How to load TextureAtlas with the AssetManager in Starling Framework?

From the Hsharma's tutorial, we have learned that using a Sprite Sheet to load the textures is crucial to ensure a great performance. Next, you may want to ask, if the Sprite Sheet is too big to be loaded at run-time, are we able to tell the users, "hey, we are loading the resources, please wait a minute" to serve as a buffer before we proceed to the next screen/activity?

Good news. Tracking the process of loading the textures or other assets is made possible with the AssetManager class in the Starling Framework. In fact, the original tutorial could be found at here. In this post, particularly, i would like to show how to load TextureAtlas with the AssetManager.

Similar to loading the normal textures, to begin loading the TextureAtlas, let's have a class EmbeddedAssets.

public class EmbeddedAssets
{
     // Texture
     [Embed(source="../media/graphics/mypng.png")]
     public static const mypng:Class;
       
     // XML

     [Embed(source="../media/graphics/myxml.xml", mimeType="application/octet-stream")]
     public static const myxml:Class;

}

In the EmbeddedAssets class, we embed the TextureAtlas and the TextureXml as usual. Yup, just embed them as usual. Then, we could just use the AssetManager to load it (with the enqueue function).

public var assets:AssetManager = new AssetManager();

.....
assets.enqueue(EmbeddedAssets); //yes, enqueue the entire class
assets.loadQueue(function(ratio:Number):void
 {
    trace("Loading assets, progress:", ratio); //track the progress with this ratio
    if (ratio == 1.0)
          initGame();
 }); 



 Finally, in the initGame and the subsequent functions, we are able to load the texture with the function getTexture. For example, assume that you have a texture named "playButton" in the TextureAtlas, you can easily load it with the line below:

 var texture:Texture = assets.getTexture("playButton");

Isn't that very convenient?

No comments:

Post a Comment