Friday, October 14, 2011

Controller Class (UnrealScript)

The Controller class is like the brains behind the entities in the Unreal Engine. It is responsible for receiving external events, process these events and decide the next action to be performed by the Pawn object that is possessed by the Controller.

The two main subclasses of Controller are AIController and PlayerController. If we want to create a character controlled by the player then we need to create a subclass of PlayerController. If the character is controlled by Artificial Intelligence then we need to create a subclass of AIController. The next image shows the subclasses of Controller in UDK:


The process of assign a Pawn to a Controller is know as Possession. There is a function in the Controller class with the name Possess() that is called when the possession happens, being a good place to do some initialization.

The code below creates a simple subclass of AIController. This new controller defines two states: Idle and Chasing. The Bot start the game in the Idle state. When it sees the player then it changes to Chasing state and begin to move towards the player.

class TestController extends AIController;

var Pawn player;

event Possess(Pawn inPawn, bool bVehicleTransition)
{
  super.Possess(inPawn, bVehicleTransition);
  //initialize Pawn Physics
  inPawn.SetMovementPhysics();
}
auto state Idle
{
   event SeePlayer(Pawn Seen)
   {      
     super.SeePlayer(Seen);
     player = Seen;
     GotoState('Chasing');
   }
}
state Chasing
{
   Begin:
      MoveToward(player); 
      goto 'Begin';
}

To test this code create a Pawn class and put the complete name (package + class) of the Controller in the property ControllerClass of the Pawn class, for example:

ControllerClass=RomeroScripts.TestController


For more information about Controller and Pawn:
Characters Technical Guide