Game Development Reference
In-Depth Information
using System;
1
using Microsoft.Xna.Framework;
2
3
4
class UnpredictableEnemy : PatrollingEnemy
{
5
public override void Update(GameTime gameTime)
6
{
7
if (waitTime <= 0 && GameEnvironment.Random.NextDouble() < 0.01)
8
{
9
TurnAround();
10
velocity.X = Math.Sign(velocity.X)
11
( float )GameEnvironment.Random.NextDouble()
5.0f;
12
}
13
base .Update(gameTime);
14
}
15
}
16
}
17
Listing 28.2
An enemy that randomly changes direction while walking
waitTime = 0.5f;
velocity.X = 0.0f;
}
28.3.2 Different Types of Enemies
We can make the patrolling enemy slightly more interesting by introducing a few
varieties. Here we can use the power of inheritance to write a few subclasses of the
PatrollingEnemy class to define different enemy behavior.
For example, we can think of an enemy that is a bit more unpredictable by
letting it change direction once in a while. At that point, we can also change the
walking speed of the enemy to some random value. We do this by defining a class
UnpredictableEnemy that inherits from the Enemy class. So, by default, it exhibits the
same behavior as a regular enemy. What we will do is override the Update method
and add a few lines of code that randomly change the direction that the enemy
is walking in, as well as its velocity. In Listing 28.2 , you can find the complete
UnpredictableEnemy class.
As you can see, we use an if -instruction to check if a randomly generated number
falls below a certain value. As a result, in a few cases the condition will yield true .
Inside the body of the if -instruction, we first turn around the enemy, and then we
calculate a new x velocity. Note that we multiply the randomly generated velocity
with the sign of the old velocity value. This is to ensure that the new velocity is set
Search WWH ::




Custom Search