Core/Math API – Rotation using FRotationMatrix to have one object face another

FRotationMatrix offers matrix construction using a series of ::Make* routines. They are easy to use and useful to get one object to face another. Say you have two objects, one of which is following the other. We want the rotation of the follower to always be facing what it is following. The construction methods of FRotationMatrix make this easy to do.

Getting ready

Have two actors in a scene, one of which should face the other.

How to do it…

  1. In the follower's Tick() method, look into the available constructors under the FRotationMatrix class. Available are a bunch of constructors that will let you specify a rotation for an object (from stock position) by reorienting one or more of the X, Y, Z axes, named with the FRotationMatrix::Make*() pattern.
  2. Assuming you have a default stock orientation for your actor (with Forward facing down the +X axis, and up facing up the +Z axis), find the vector from the follower to the object he is following, as shown in this piece of code:
    FVector toFollow = target->GetActorLocation() - GetActorLocation();
    FMatrix rotationMatrix = FRotationMatrix::MakeFromXZ( toTarget, GetActorUpVector() );
    SetActorRotation( rotationMatrix.Rotator() );

How it works…

Getting one object to look at another, with a desired up vector, can be done by calling the correct function, depending on your object's stock orientation. Usually, you want to reorient the X axis (Forward), while specifying either the Y axis (Right) or Z axis (Up) vectors (FRotationMatrix::MakeFromXY()). For example, to make an actor look along a lookAlong vector, with its right side facing right, we'd construct and set FRotationMatrix for it as follows:

FRotationMatrix rotationMatrix = FRotationMatrix::MakeFromXY( lookAlong, right );
actor->SetActorRotation( rotationMatrix.Rotator() );
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.143.31