Friday, November 11, 2011

Drawing the HUD (UnrealScript)

HUD (Head Up Display) is a kind of panel used to display information to the player using image and text. There are two ways of drawing the HUD, the most common is using a Canvas class that has functions to draw graphics and text. The other option is using the Scaleform GFx that integrates scenes built in Flash into the UDK.

The image below shows the HUD subclasses in UDK:


I made an example of HUD that draws an image, a text and a rectangle. This example draws a health bar that decreases and changes color as the time goes, as can be seen in the images:




Code sample:
class TestHUD extends UTHUD;

var CanvasIcon clockIcon;
var int clock; 

event PostBeginPlay()
{
   SetTimer( 1, true );
   clock = 30;
}

function Timer()
{
  clock--;

  if(clock <= 0)
  {     
     clock = 30;
  }
}

function DrawHUD()
{
   super.DrawHUD();    

   Canvas.DrawIcon(clockIcon, 0, 0);     

   Canvas.Font = class'Engine'.static.GetLargeFont();      
   Canvas.SetDrawColor(255, 255, 255); // White
   Canvas.SetPos(70, 15);
   
   Canvas.DrawText(clock);

   if(clock < 10)
   {
     Canvas.SetDrawColor(255, 0, 0); // Red
   }
   else if (clock < 20)
   {
     Canvas.SetDrawColor(255, 255, 0); // Yellow
   } 
   else 
   {
     Canvas.SetDrawColor(0, 255, 0); // Green
   }
 
   Canvas.SetPos(200, 15);   
   Canvas.DrawRect(20 * clock, 30);      

}
defaultproperties
{
 clockIcon=(Texture=Texture2D'UDKHUD.Time')  
}

Now we need to create a subclass of GameInfo to reference the new HUD class. Just a note, if you are using UTGame/UTHUD classes you must set true in the bUseClassicHUD property of the UTGame subclass or your HUD will not work.
class MyUTGame extends UTGame;

defaultproperties
{    
   HUDType=class'RomeroScripts.TestHUD'
   bUseClassicHUD=true
}

For more information about HUD:
HUD Technical Guide