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. While you've done some great work on your SpriteManager, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access