O'Reilly logo

Learning XNA 3.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 Evading Sprite

You now have two types of automated sprites in your application: one that moves across the screen without changing direction, and one that moves across the screen but changes direction slightly to chase the player.

In this section, you'll build one more type of sprite that is similar to the chasing sprite, but this one will actually try to avoid the player. Why would you want to write a sprite that avoids the player? This sprite type will be used for something that the player will want to run into (maybe a power-up, or extra life or something), so the sprite will tease the player by letting her get close to it but then, when she gets too close, taking off in another direction. This should add a nice different element to the game, as well as making it more challenging.

Let's get started. Add a new class to your project, and call it EvadingSprite.cs. The code for this sprite will be very similar to the code you just wrote for the ChasingSprite—so similar, in fact, that it will be easier to start with that code than to start from scratch. Remove the code generated for you in the EvadingSprite class and replace it by copying the code in the ChasingSprite class and pasting that code into the EvadingSprite.cs file. You'll need to change the name of the class from ChasingSprite to EvadingSprite and also change the names of the constructors. Your EvadingSprite.cs file should now look like this:

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

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