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

Chapter 4. User Input and Collision Detection

As cool as it was to see a nice-looking set of rings spinning around and realize that you’d made that happen yourself, there’s a long way to go with XNA. Although the animated object looked nice, it didn’t do anything, and you had no control over its movement. What fun is a game where there’s no interaction on the part of the player? In this chapter, we explore user input and collision detection as ways to make your game actually do something besides look nice and pretty.

This chapter uses the code that you built at the end of Chapter 3 (the animated three rings sprite). Open that project and make the changes discussed in this chapter there.

More Sprites

If you’re going to have a user-controlled object and build in some collision detection against other objects, you’re going to need at least one more object on the screen. Let’s add another animated sprite to your project.

Instead of using the same three rings image, we’ll use a different image for the second animated sprite. Along with the source code for this book, you’ll find the code for this chapter. In the AnimatedSprites\AnimatedSprites\AnimatedSpritesContent\Images folder, you’ll find an image called skullball.png. Add that image file to the project in the same way you’ve added previous image files (right-click the Content\Images folder in Solution Explorer, select AddExisting Item, and then browse to the skullball.png image and add it to the solution).

Next, you’ll need to create a number of variables that will allow you to draw and animate the skull ball sprite. These variables should look somewhat familiar to you, as they are very similar to the ones you used in Chapter 3 to draw and animate the three rings sprite. Add the following class-level variables at the top of your Game1 class:

Texture2D skullTexture;
Point skullFrameSize = new Point(75, 75);
Point skullCurrentFrame = new Point(0, 0);
Point skullSheetSize = new Point(6, 8);
int skullTimeSinceLastFrame = 0;
const int skullMillisecondsPerFrame = 50;

The skull ball image frames are 75×75 pixels, and there are six columns and eight rows in the sprite sheet. You’ll want to change the names for the variables you’re using in this game to draw and animate the three rings now, to avoid confusion due to having multiple sprites in your game. Add the word “rings” at the beginning of each variable name, and change all the references to those variables; this will help you keep things straight as you move through this chapter. The rings variables should now be declared as:

Texture2D ringsTexture;
Point ringsFrameSize = new Point(75, 75);
Point ringsCurrentFrame = new Point(0, 0);
Point ringsSheetSize = new Point(6, 8);
int ringsTimeSinceLastFrame = 0;
int ringsMillisecondsPerFrame = 50;

Compile the project and make sure that you don’t have any compilation errors due to the renaming of these variables. If you do, remember that the variable names should be the same as in the previous project; you’ve just added the word “rings” to the beginning of each name. Fix any errors until the game compiles properly.

Chapter 5 will walk you through some basic object-oriented design principles that will make adding new sprites much easier. For now, you just want to get to some user input and collision detection, so let’s add the code for the skull ball animation.

Load your skull ball image into the skullTexture variable in the LoadContent method in the same way you loaded your three rings image:

skullTexture = Content.Load<Texture2D>(@"Images\skullball");

Next, add the code that will move the current frame through the sequence of frames on the sprite sheet. Remember, this is done in the Update method. Because you’re already doing this with the three rings sprite, you can just copy the code for the three rings animation and rename the variables to make it work:

skullTimeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (skullTimeSinceLastFrame > skullMillisecondsPerFrame)
    skullTimeSinceLastFrame −= skullMillisecondsPerFrame;
    if (skullCurrentFrame.X >= skullSheetSize.X)
        skullCurrentFrame.X = 0;
        if (skullCurrentFrame.Y >= skullSheetSize.Y)
            skullCurrentFrame.Y = 0;

Finally, you need to draw the sprite on the screen. Remember that all drawing takes place in the Draw method. Once again, you already have code in that method that draws the three rings sprite, and you can just copy that code and change the variable names to draw the skull ball image. So that the two sprites aren’t drawn on top of each other, change the second parameter of the skull ball’s Draw call to draw the image at (100, 100) rather than at (0, 0). Your skull ball Draw call should look like this:

spriteBatch.Draw(skullTexture, new Vector2(100, 100),
    new Rectangle(skullCurrentFrame.X * skullFrameSize.X,
        skullCurrentFrame.Y * skullFrameSize.Y,
        Color.White, 0, Vector2.Zero,
        1, SpriteEffects.None, 0);

Compile and run the application at this point and you’ll see both images animating, as shown in Figure 4-1.

Two animated sprites doing their thing

Figure 4-1. Two animated sprites doing their thing

Not bad! In only a few moments, you’ve added a completely new animated sprite to your game. Software development often yields moments of excitement and accomplishment, but that feeling seems to be amplified with game development because of the added visual (and later auditory) senses involved. These two animating objects look pretty cool, but things are only just getting interesting. Now you’ll learn how to control the objects on the screen and give your application some user interaction.

User input in XNA is done via a combination of multiple device options: the keyboard, the mouse, the Xbox 360 controller, Xbox 360 peripherals, and the Windows Phone 7 Series touch screen and accelerometer. Mouse input is never available on the Xbox 360 or Windows Phone 7.

In this chapter, you’ll add support for the keyboard, the mouse, and the Xbox 360 controller into your game.

In the previous chapter, we discussed polling versus registering for events. The difference between the two strategies is really never more visible than when dealing with input devices. Traditional Windows programmers are used to registering for events such as key-down events or mouse-move events. With this programming model, the application performs some actions and then, when the application has idle time, the messages are pumped into the application and the events are processed.

In game development, there is no idle time, so it would be too expensive to enable developers to register for events. Instead, it is up to you as the developer to constantly poll input devices asking whether the player has performed any actions on those devices.

That’s a slightly different way of looking at input and other messages and events, but once you figure it out, game development will make a lot more sense.

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