Now that we have created a simple project that draws an image on the screen, we should discuss some of the ways we can manipulate how we draw. Consider the following line of code:
SpriteBatch.Draw(Texture, DestinationRect, SourceRect,
Color, Rotation, Origin, SpriteEffects, Layer);
SpriteBatch.Draw(Texture, Position, SourceRect, Color, Rotation,
Origin, Scale, SpriteEffects, Layer);
These are two of the more important overloads to the Draw method. I suggest you play around with them to see what kind of effects you can get. The destination rectangle is a way of explicitly telling the SpriteBatch what screen space your sprite will take up. The source rect is a way of telling the SpriteBatch what pixels to use from the texture. For example, to draw just the first ball in our image you would use a rectangle of Width and Height of 32 and X and Y positions of zero. Color is the tint color applied to the object, rotation rotates the object about the origin which is in pixels (0,0 being the top left corner) of the source image. Sprite effects allows you to flip the image horizontally and/or vertically. The layer provides Z-Ordering so that you can tell the SpriteBatch how to draw your objects.
Okay, so let’s animate this thing! First, add a few items at the top of the class, underneath the Texture2D object.
Rectangle srcRect = new Rectangle(0, 0, 32, 32);
float currentRect = 0;
float speed = 0.25f;
Then in the update, we have to update our members so that we change the rectangle and speed as necessary. We know that there are only five circles, so we can hardcode it.
// If we have gone over the max, cap
// and reverse!
if (currentRect > 5)
{
currentRect = 5;
speed *= -1;
}
// If we have gone under the min,
// cap and reverse.
else if (currentRect < 0)
{
currentRect = 0;
speed *= -1;
}
// Update the current counter
currentRect += speed;
// Set the X coordinate
srcRect.X = (int)currentRect * 32;
And finally we update the Draw method to use the new override with a source rectangle!
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
spriteBatch.Draw(spriteSheet, Vector2.Zero, srcRect, Color.White, 0.0f,
Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);
spriteBatch.End();
And that’s it! You now have an animated sprite using a sprite sheet! One final note about the SpriteBatch object. Always try and stuff as many draw calls as possible between as few Begin/End calls as possible. The SpriteBatch is most efficient when it has many things to draw and doesn’t have to setup the GraphicsDevice many times.
Flix Viewer (ClickOnce) (629) - 666.9 kB
