AS3: SpriteSheet Class – Extracting Sprites

If you haven’t already read the intro to this tutorial, you can find it here. In it we are introduced to sprite sheets, what they are, and some examples for where to use them.

One of those examples included combining many assets into a single sprite sheet. We can then extract a portion of this bitmap as its own unique element and use it as if we had loaded it separately. This kind of sprite sheet could be used for a variety of things. Maybe you’re designing an interface and you want to group similar UI elements in order to load them all at once. You could also find yourself developing a game in which there are many items for the player to collect and you need an easy way to organize them. The example below shows such a sprite sheet:

Sprite sheet of items in SNES game Zelda
Images © Nintendo

Extracting Sprites

Like we mentioned above, this kind of sprite sheet would be the most useful to us if we had a way to extract an individual element from it. Thankfully with the help of some code and a little Triforce of Wisdom we can do just that.

Note: From here on out I’ll be referring to my SpriteSheet class. It is available here for reference.

This example uses the same sprite sheet that we first looked at in this tutorial. Click an area of it to extract it and blow it up, showing off its 16-bit glory. In the code below we will attempt to extract a sprite in the same way.

Actionscript

1
2
3
4
import com.bensilvis.spriteSheet.SpriteSheet;

import flash.display.Bitmap;
import flash.display.Sprite;

You will need to import the custom SpriteSheet class like this in order to have access to it, along with these other imports.

Actionscript

1
2
3
4
5
var currentSprite:SpriteSheet = new SpriteSheet(sheet, 20, 20);

var image:Bitmap = new Bitmap();
image.bitmapData = currentSprite.DrawTile(0);
addChild(image);
What we do here is:
  1. Instantiate a copy of the SpriteSheet class
  2. Extract tile ‘0’ with the DrawTile function
  3. Add the extracted sprite to the stage

Pretty simple huh?

Actionscript

1
var currentSprite:SpriteSheet = new SpriteSheet(sheet, 20, 20);

If we have imported the SpriteSheet class then we can create a new copy of it and access all of its functionality. The constructor takes 3 parameters:

SpriteSheet(tileSheetBitmap:Bitmap, width:Number = 16, height:Number = 16)
  • tileSheetBitmap: the Bitmap of the sprite sheet we will use
  • width: the width of  tiles in the sheet
  • height: the height of tiles in the sheet

Assuming we have loaded and have access to our sprite sheet Bitmap, we pass it to our new class as variable ‘sheet’.

The width and height parameters need to be set to the size of the sprites in the sprite sheet (not the entire sprite sheet). In this particular example both dimensions are 20 pixels.

Note: Each tile in your sprite sheet must have the same dimensions in order to work properly.

Actionscript

1
2
3
var image:Bitmap = new Bitmap();
image.bitmapData = currentSprite.DrawTile(0);
addChild(image);

Here we create a new blank Bitmap to contain the pixel data of the sprite we’re going to copy. Next we call the DrawTile function of our recently created SpriteSheet class and pass it an integer. In short, this tells the class to locate an area of the sprite sheet Bitmap based on the parameter we just sent, and extract a rectangle of pixels from it determined by the width and height that we specified in the constructor. We then hand off this data to our blank Bitmap as its new bitmapData.

After that we simply attach the new Bitmap to the stage, which now displays sprite ‘0’, to use how we please.

Numbering of a sprite sheet:

In the example above we extract from our sprite sheet by passing the drawTile function an integer of ‘0’. This number represents a particular tile on our sprite sheet. When numbering our sprites we start at the top-left and increment by one for each tile down a row progressively. Since we’re starting the count with zero we need to offset the tile’s number by one (tile number – 1). Therefore with ‘0’ our example is effectively extracting the very first sprite.

Sometime in the next couple of days I will post an article with tips for creating sprite sheets. 🙂

Concluding..

This example may have been a little trickier than some in the past because it involves using a custom class, so feel free to download the complete Flex project to the top example!

Stay tuned for the next tutorial which covers sprite sheet animation!

Ben

14 thoughts on “AS3: SpriteSheet Class – Extracting Sprites

  1. Pingback: Source Code For Sprite Sheet Animator « Game Development

  2. Lea

    Great tutorial. Just what I was looking for. But what if you have variable tile size how would you handle that?
    PS: really looking forward to the next tutorials. Would love to help in anyway but I doubt my AS3 kung fu is strong enough.

  3. Pingback: AS3 Code Libraries (APIs) | bytecoderz blog

  4. Olivier

    Just needed this, thanks for saving me the time to write it myself 🙂

    I made a small change, since half the time i actually have bitmapdata instead of a bitmap to feed it, i made it able to use both. The class check i made isnt perfect, but serves the purpose.

    http://pastebin.com/QBK6aTZU

  5. Steve

    Maybe I’m thick, but how exactly do you load the sprite bitmap in the first place? I’ve found numerous links around the net, but none of the code seems to work for me. I’ve tried using Loader() and all sorts, but nothing works properly.

  6. Jose

    Hey Ben, thanks for this handy class. I’m going to throw in a dispose method in there to clear out the bitmap data when it’s done. I encourage to continue writing tutorials, looking forward to the animation one, thanks again!

  7. Zach

    Just to echo what Jose said, I would /highly/ recommend touching up the SpriteSheet class to include two things – an event listener for the REMOVED_FROM_STAGE event and an appropriate remove method that properly disposes of the BitmapData objects.

    Here’s my modification: http://www.copypastecode.com/80004/

    The difference is huge. I’m using this in a tower defense game and memory usage would hover at ~70MB when in the map selection screen. During a level, usage would jump to ~120MB, but then climb to around ~140MB upon completion. This was cumulative, so that each success level would add another 70MB or so, eventually resulting in the game taking up around 4GB!!! With the modifications listed above, the usage returns to a reasonable level upon removing all of the sprite sheets from the stage. See the memory graphs below for comparison.

    http://i.imgur.com/vu986.png
    http://i.imgur.com/jJcMn.png

    Otherwise, this has been a great utility class! Thanks for taking the time to write and share it.

  8. Pingback: Using Sprite Sheets in AS3 | NNGAFOOK.com | Blog

  9. Pingback: Очень много полезных штук для AS3 #2 | BomBear

  10. Joar

    Hello! Excuse a VERY basic as3-user, I’m currently doing my first learning project.
    Your code is exactly what I want, but I’m unable to implement it. The “download source” folder doesn’t seem to have a .fla in it, from which I could make my way to an implementation.
    What am I missing? Will you release a .fla, or a tutorial on implementation made for infants?
    Again, please excuse my ignorance…

Leave a Reply

Your email address will not be published. Required fields are marked *