tl;dr: You'll want to use a sprite sheet and create an animated sprite with a delegate to notify the owner when the animation has completed.
Let's break down the steps and design this out.
User Story
When a bullet collides with an asteroid, the asteroid should explode and disappear.
Feature Breakdown
- Detect collision between
Bullet
and Asteroid
- Play destroy animation on
Asteroid
's sprite.
- Remove
Asteroid
Class Breakdown
AnimatedSprite
: Displays an animated Sprite
at a given position onscreen at a given rate
Hitbox
: Defines an object's collidable area, and can be used to determine if two hitboxes collide
Bullet
: Projectiles shot by the player containing a Sprite
and a Hitbox
Asteroid
: Obstacles to be shot by the player containing an AnimatedSprite
and a Hitbox
Walkthrough
I'm assuming you already have solved 1. Detect collision between Bullet and Asteroid
, so let's jump to step 2.
There is a fairly comprehensive article regarding Sprite animation on MSDN that you should read before continuing development, but I'll try to sum it up here.
We're going to be using a sprite sheet for the asteroid's animation. The reasoning here is that a sprite sheet has much less memory overhead than discrete images (due to graphics card implementation and other stuff that you don't really need to worry about for this example).
The basic premise is to create a rectangle and only render that portion of the image. You can think of it as a film reel: There are many individual frames to create the motion, but you only see one at a time. Each update loop, a timer in the AnimatedSprite
will be increased, and once it reaches the desired frame-rate, we will move the rectangle to the next part of the animation.
We'll want to modify the sample code above, adding a function, Play()
and a delegate, AnimationComplete
. Additionally, we'll only want to play the animation once, stop our animation, and call AnimationComplete
. Then, in Asteroid, we'll want to pass a function, Destroy()
to the delegate we created in AnimatedSprite
. This means, once the animation is complete, the AnimatedSprite
will call Destroy()
on the asteroid (which is what we're trying to do).
Summary
Here's the task breakdown:
Detect collision between Bullet
and Asteroid
- Create an
AnimatedSprite
class to handle our animation
- Should begin paused on the first frame
- Should be able to begin playback via a function call
- Should call a delegate once the animation is complete
Create a function to allow Asteroid
to destroy itself