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 Chasing Sprite

As mentioned previously, when it comes to computer-controlled objects, the goal of any game is to make those objects appear intelligent to the point where a user may not be able to tell the difference between an object controlled by a human and an object controlled by a computer. We clearly aren’t even close to that.

The automated sprites you’ve added do nothing more than move forward in a straight line. You’ve done some great work on your SpriteManager, but we haven’t discussed how to do anything to improve the movement of your automated sprites.

Let’s create a couple of different objects that do something a little more intelligent than simply moving in a straight line.

In this section, you’ll create a new sprite type that will chase your user-controlled object around the screen. You’ll do this with the following very simple chase algorithm:

if (player.X < chasingSprite.X)
    chasingSprite.X −= 1;
else if (player.X > chasingSprite.X)
    chasingSprite.X += 1;

if (player.Y < chasingSprite.Y)
    chasingSprite.Y −= 1;
else if (player.Y > chasingSprite.Y)
    chasingSprite.Y += 1;

Essentially, the algorithm compares the position of the player with that of the chasing sprite. If the player’s X coordinate is less than the chasing sprite’s X coordinate, the chasing sprite’s coordinate is decremented. If the player’s X coordinate is greater than the chasing sprite’s X coordinate, the chasing sprite’s X coordinate is incremented. The same is done with the Y coordinate.

To implement ...

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