Sunday, October 23, 2011

Using Vectors in UnrealScript

A vector in UnrealScript is a structure that contains the values X, Y and Z. The use of vectors simplifies many things in 3D game programming. Vectors can be used to represent position, velocity, acceleration, distance, direction...

UnrealScript has some utility functions for vectors. The two most used are:
  • function float VSize( vector A ): Returns the lenght of the vector.
  • function vector Normal( vector A ): Returns a unit vector (lenght = 1).

The Actor class has a vector called Location that represents its current position in the 3D world.

The example below show the various uses of vectors. An Actor moves toward a random position. When it arrives at the destination a new position is chosen.
class TestVectors extends Actor
      placeable;
     
var vector vDestination;

const SPEED = 100; // UU/Sec (Unreal Unit / Second)
     
function SetNewDestination()
{
    //choose random position
    vDestination.X = -500 + Rand(1001); //-500 to 500
    vDestination.Y = -500 + Rand(1001); //-500 to 500
    vDestination.Z = 150 + Rand(101); //150 to 250
    
    worldinfo.game.broadcast(self, "NEW DESTINATION: " $ vDestination);
}     

event PostBeginPlay()
{
    SetNewDestination();
}

//This function is called every frame by Unreal Engine
event Tick(float DeltaTime)
{   
   local vector vDistance;
   local vector vDirection;
   local vector vVelocity;
   local vector vStep;
   
   vDistance = vDestination - Location;   
   
   //Check if the Actor has reached the destination
   if( VSize( vDistance ) < SPEED )
   {
        SetNewDestination();
        vDistance = vDestination - Location;
   }
   
   vDirection = Normal( vDistance );      
   vVelocity = vDirection * SPEED;
   vStep = vVelocity * DeltaTime;
   Move( vStep );    
}
     
defaultproperties
{        
    begin object Class=StaticMeshComponent Name=Model3D
        StaticMesh = Pickups.UDamage.Mesh.S_Pickups_UDamage        
    end object
    
    Components.add(Model3D);
}