O'Reilly logo

Learning XNA 4.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating an Automated Sprite Class

Now that you have a class that allows the user to control a sprite, it’s time to add a class that will generate an animated sprite that moves on its own. Add a new class to your project by right-clicking on the project in Solution Explorer and selecting AddClass. Name the class file AutomatedSprite.cs. Once the file is ready, mark the new class as a subclass of your Sprite class:

class AutomatedSprite: Sprite

Add the same XNA namespaces as before, but without the input namespace because you won’t be gathering input from any devices in this class:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

Next, add two constructors for the AutomatedSprite class. These constructors will be identical to the ones used for the UserControlledSprite class:

public AutomatedSprite(Texture2D textureImage, Vector2 position, Point frameSize,
    int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed)
    : base(textureImage, position, frameSize, collisionOffset, currentFrame,
    sheetSize, speed)
{
}

public AutomatedSprite(Texture2D textureImage, Vector2 position, Point frameSize,
    int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed,
    int millisecondsPerFrame)
    : base(textureImage, position, frameSize, collisionOffset, currentFrame,
    sheetSize, speed, millisecondsPerFrame)
{
}

Your automated sprite will use the speed member of the base class to move around the screen. This will be done through an overridden direction property because ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required