Reputation: 40336
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?
Upvotes: 3
Views: 6750
Reputation: 9461
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:
Upvotes: 10
Reputation: 2104
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.
Upvotes: 1