3

I have an image mySprite.png. The image is a 5x5 grid of 32x32 px sprites. This image has been loaded into the project's library.

Assuming I have a render() function inside a class, how would this class draw itself as a single sprite from this sprite sheet resource?

soundly_typed
  • 39,257
  • 5
  • 28
  • 36

2 Answers2

10

The short answer is that you will want to use BitmapData.copyPixels() to copy only a small section from your source sprite sheet to your display sprite that is actually on the screen.

Something like:

private function DrawSpriteIndex( displayBitmap:Bitmap, spriteSheet:Bitmap, spriteIndex:int ):void {
  var spriteW:int = 32;
  var spriteH:int = 32;
  var sheetW:int = 5;

  displayBitmap.bitmapData.copyPixels(spriteSheet.bitmapData, 
                                       new Rectangle( (spriteIndex % sheetW) * spriteW, Math.floor(spriteIndex / sheetW) * spriteH, 32, 32),
                                       new Point(0,0)
                                      );
}

You may find these links helpful -- they helped me when I was learning this:

Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143
HanClinto
  • 9,423
  • 3
  • 30
  • 31
1

Another possible method would be to put a 32x32 mask over the sheet and just move the sheet around.

It would work something like (pseudo-code):

var spriteMask:Sprite = new Sprite();
spriteMask.graphics.drawRect(0,0,32,32);
spriteSheetContainer.mask = spriteMask;

function render():void {    // this function is on the container of the sprite sheet (spriteSheetContainer in this example)
    // run offsetX & Y iteration logic.  I would assume something that uses a frame counter, modulus, and the sprite layout grid dimensions
    _spriteSheet.x = offsetX;    // move the sprite around under the mask
    _spriteSheet.y = offsetY;
}

It's crucial to have the mask on a container of the sprite sheet and not the sprite sheet itself, so that you can move the sprite sheet independent of the mask.

RickDT
  • 2,104
  • 1
  • 23
  • 25
  • 2
    There are some pretty major performance ramifications of doing this, as the Flash player is still drawing the entire image, even though you don't see it. – Tyler Egeto Jul 28 '09 at 18:44