Wednesday, October 12, 2011

Introduction to States in UnrealScript

One of the great advantage of UnrealScript is that it supports the use of States within the language. The concept of Finite State Machine is essential to game programming.

Let's imagine a simple example. We have an enemy in the game that can be in one of three states: Chasing, Fleeing and Roaming. The actions of the enemy will be directly influenced by their current state, for example, if he is Chasing, should move toward the player, if he is Fleeing, should move away from the player, if he is Roaming, should move randomly.

In this example we can define some transitions between the states as follows:
  • The enemy started the game in the state Roaming;
  • If the enemy is in the state Roaming and the player gets near the enemy, he goes to the state Chasing;
  • If the player shoot the enemy he switches to state Fleeing;
  • If the enemy is Fleeing and the player is far then switches to state Roaming;
The pseudocode below shows how states are defined in UnrealScript. In each state was defined a different version of a function called "moveAI()". When this function is called from an object of type Enemy the version that will run depend on the current state of this object.
class Enemy extends Actor;

//The word "auto" defines the initial State
auto state Roaming
{
  function moveAI(float DeltaTime)
  {
    //move randomly
    //If player is near:
    //  GotoState('Chasing');
  }
} 
state Chasing
{
  function moveAI(float DeltaTime)
  {
    //move towards player
  }
}
state Fleeing
{
  function moveAI(float DeltaTime)
  {
    //move away from the player
  }
}

For more information about States:
UnrealScript States