Game Development Reference
In-Depth Information
28.3 A Patrolling Enemy
The rocket is a type of enemy that basically has no intelligent behavior. It flies from
left to right or vice versa until it flies out of the screen, and then it resets itself. We
can also add enemies that are slightly smarter, such as a
patrolling
enemy. Let us
setup a few different types of patrolling enemies that we can add to our game.
28.3.1 The Basic
PatrollingEnemy
Class
The
PatrollingEnemy
class is quite similar to the
Rocket
class. We want the patrolling
enemy to be animated, so it will inherit from the
AnimatedGameObject
class. Second,
we need to define the
behavior
of the enemy inside the overridden
Update
method.
The basic behavior of the patrolling enemy is that it walks from left to right and
back again. If the enemy character reaches a gap, or a wall tile, the enemy will stop
walking, wait for some time, and turn around again. We can then place enemies on
arbitrary positions in the level. For the player, we have defined some rudimentary
physics like falling and jumping. We will not do that for the
Enemy
class, since the
enemies we will define for this game will only walk from the left to the right and
back again.
In the constructor of the
PatrollingEnemy
class, we load the main animation for
the patrolling enemy character (which is an angry-looking flame). Initially, we set
a positive velocity so that the enemy character starts walking to the right. Also, we
initialize another member variable called
waitTime
that will maintain how long the
enemy has been waiting on one of the edges of the platform that it is walking on.
waitTime = 0.0f;
velocity.X = 120;
this
.LoadAnimation("Sprites/Flame/spr_flame@9", "default",
true
);
this
.PlayAnimation("default");
Inside the
Update
method, we have to distinguish between two cases: the enemy
is walking or waiting. We can distinguish between these to states by looking at the
waitTime
variable. If this variable contains a positive value, the enemy is apparently
waiting. If the variable contains a value of zero or smaller, the enemy is walking.
When the enemy is waiting, we do not have to do much. Just like we did in the
Rocket
class, we subtract the elapsed game time from the
waitTime
variable. If the
wait time has reached zero, we have to turn around the character. Here is the code
that handles this:
if
(waitTime > 0)
{
−
waitTime
=(
float
)gameTime.ElapsedGameTime.TotalSeconds;
if
(waitTime <= 0.0f)
TurnAround();
}