O'Reilly logo

Beginning Windows® Phone 7 Application Development: Building Windows® Phone Applications Using Silverlight® and XNA® by Robert Fonseca-Ensor, Karli Watson, Nick Lecrenski

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

UPDATING GAME STATE

As discussed earlier, the Update() method of the Tank game is responsible for updating the state of the game's world in response to various types of inputs, especially the passing of time. But what do we mean by “the state of the world”? Software uses variables to hold state, and fields (that is, class-level variables) represent more persistent state. But none of the fields you've used so far represent the conceptual world that is the Tank game.

Here are some examples of conceptual things that a game could include, along with potential types that could hold the state for these variables in an XNA game:

CONCEPT TYPE
Position Vector2
Speed Vector2
Acceleration Vector2
Angle/direction float
Alive/dead bool
Score int
Health points/lives int
The last time something occurred DateTime
How long something might take TimeSpan

The Versatility of Vectors

As it turns out, that's the hard way to translate vectors. The Vector2 class in XNA has all sorts of nifty methods. Mathematically, you use it to add one vector to another. As it turns out, Vector2 overloads the plus operator. This means that even though an instance of Vector2 isn't a number, you can simply add two Vector2s together. And you can use x += y as shorthand for x = x+y. Here's how you could refactor the code to make use of this versatility:

protected override void Update(GameTime gameTime) { // Allows the game to exit GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);  ...

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