XNA Game Programming—Enemy


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Create a third person shooter game

© 2008 Lobão, et. al.

Enemy

The Enemy class is the one that has the enemy NPC's logic and attributes. Figure 12-10 exhibits a spider model used as an enemy in the game.



Figure 12-10. An alien spider model. Courtesy of Psionic (http://www.psionic3d.co.uk).


Differently from the player, the enemy is computer controlled, so you need to implement its AI. The enemy's AI is simple, having only four different states: Wandering, Chasing Player, Attacking Player, and Dead. Figure 12-11 shows the diagram of the AI built for the enemies.


Image:BegXNAGameProgfig12-11.jpg
Figure 12-11. Enemy AI diagram


In the AI diagram in Figure 12-11, each circle represents a different enemy state, and the arrows represent the actions that make an enemy change its state. The enemy's AI starts in the Wandering state. In this state, the enemy keeps moving around the map randomly looking for the player. Whenever the enemy sees the player or gets shot by the player, he changes his state to Chasing Player. In the Chasing Player state, the enemy moves closer to the player until he is near enough to attack the player. When that happens, the enemy state is altered to Attacking Player. In this state, the enemy attacks the player successively until the player dies or the player runs. If the player tries to run from the enemy, the enemy's state is changed back to Chasing Player. Notice that once the enemy starts to chase the player, the enemy stays in a cycle between the states Chasing Player and Attacking Player, not returning to the Wandering state.

Each enemy has an attribute to store his current state, among an enumeration of possible states.

// Possible enemy states
public enum EnemyState
{
   Wander = 0,
   ChasePlayer,
   AttackPlayer,
   Dead
}
 
// Current enemy state (default = Wander)
EnemyState state;

For each one of the possible enemy states you'll declare some attributes and create a method to execute this state. To control the transitions between the enemy states, you'll overwrite the Update method of its base class.


Previous_Page_.gif Next_Page_.gif


Personal tools