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 a User-Controlled Sprite Class

Now you’ll create a class that derives from your base Sprite class, adding functionality to let the user control the sprite. Add a new class to your project by right-clicking on the project in Solution Explorer and selecting AddClass. Name the new class file UserControlledSprite.cs. Once the file is ready, mark this class as a subclass of the Sprite class:

class UserControlledSprite: Sprite

Next, you’ll need to add some XNA using statements. Use the same ones as you did in the Sprite base class, plus an additional one (Microsoft.Xna.Framework.Input) that will allow you to read data from input devices:

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

Next, add the constructors for the UserControlledSprite class. These will be basically the same as the constructors for the Sprite class and will just pass the parameters on to the base class:

public UserControlledSprite(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed) : base(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed) { } public UserControlledSprite(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) { } ...

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