Monday, February 27, 2012

Using Physics in UnrealScript

The code below shows an enumeration in the Actor class that indicates the possible types of physics that an Actor can use.
//Extract from Actor class

var(Movement) const enum EPhysics
{
    PHYS_None,
    PHYS_Walking,
    PHYS_Falling,
    PHYS_Swimming,
    PHYS_Flying,
    PHYS_Rotating,
    PHYS_Projectile,
    PHYS_Interpolating,
    PHYS_Spider,
    PHYS_Ladder,
    PHYS_RigidBody,
    PHYS_SoftBody, 
    PHYS_NavMeshWalking, 
    PHYS_Unused,
    PHYS_Custom,    
} Physics;

I didn't find any official reference about the meaning of each of these types. To define the physic type of an Actor use the function SetPhysics() passing as parameter one of the enumeration values, as in the example below:
SetPhysics(PHYS_Projectile);

To initialize the physics of a Pawn use the function SetMovementPhysics() that has the following code:
//Extract from Pawn class

function SetMovementPhysics()
{
    // check for water volume
    if (PhysicsVolume.bWaterVolume)
    {
        SetPhysics(PHYS_Swimming);
    }
    else if (Physics != PHYS_Falling)
    {
        SetPhysics(PHYS_Falling);
    }
}

When an object of the Pawn class is with the physics type PHYS_Falling he is affected by gravity and will fall until touch a ground when turns to PHYS_Walking. In the PHYS_Flying type, the Actor is not affected by the effect of gravity. In the PHYS_Rotating type only the rotation of the actor changes and the location doesn't change.

The Actor variables most used by the physics system are the Velocity and Acceleration vectors that change the position of the Actor. For rotation we have the variable RotationRate that defines the speed of rotation. The actor also had the variable DesiredRotation, but it was moved to the Pawn class. This variable is used to rotate a Pawn smoothly until it reaches the specified rotation in DesiredRotation.

I did a very simple example that only changes the physics type of the player to PHYS_Flying. The following code defines a new GameInfo, to test it is necessary to set the Game Type in the editor as UTGameFlying.
class UTGameFlying extends UTGame;

function StartMatch()
{ 
 local UTPlayerController playerController;
 
 super.StartMatch();
 foreach LocalPlayerControllers(class 'UTPlayerController', playerController) 
 {
    if( playerController.pawn != None ) 
    {            
      playerController.pawn.SetPhysics(PHYS_Flying);            
    }
 }
}


For more information about Physics in UDK:
Physics Home