版权声明:本文为CSDN博主「wblong_cs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
FRotator(欧拉角)
FRotator(Pitch, Yaw, Roll)
对应源码为
// 左手法则
struct FRotator
{
public:
/** Rotation around the right axis (around Y axis), Looking up and down (0=Straight Ahead, +Up, -Down) */
float Pitch;
/** Rotation around the up axis (around Z axis), Running in circles 0=East, +North, -South. */
float Yaw;
/** Rotation around the forward axis (around X axis), Tilting your head, 0=Straight, +Clockwise, -CCW. */
float Roll;
}
三个参数分别为:
Pitch:俯仰角,即绕 Y 轴旋转;Yaw:偏角,即绕 Z 轴旋转;Roll:滚角,即绕 X 轴旋转。
实例 1
// 绕 z 轴旋转 10 度
FRotator rotator(0, 10, 0);
AActorT->SetActorRotation(rotator);
实例 2
// 左手法则
auto cameraRightVector = GetActorRotation().RotateVector(FVector::RightVector);
auto cameraUpVecotor = GetActorRotation().RotateVector(FVector::UpVector);
auto cameraForwardVector=(cameraRightVector ^ cameraUpVecotor);
先返回这个 Actor 的 RootComponent 的 Rotator,
然后通过这个 Rotator 旋转指定的向量
FQuat(四元数)
FQuat(FVector Axis, float AngleRad)
源码如下
struct FQuat
{
public:
/** The quaternion's X-component. */
float X;
/** The quaternion's Y-component. */
float Y;
/** The quaternion's Z-component. */
float Z;
/** The quaternion's W-component. */
float W;
}
利用四元数进行旋转,其中调用的构造函数为
FQuat(FVector Axis, float AngleRad)
创建和初始化一个新的四元数(根据给定轴旋转 a 弧度)。
实例 1
// 绕 z 轴旋转 45 度
FQuat quat = FQuat(FVector(0, 0, 1), PI / 4.f);
GetOwner()->SetActorRotation(quat);
实例 2
FQuat axisRot(FVector::RightVector, FMath::DegreesToRadians(90));
SetActorRotation((GetActorRotation().Quaternion() * axisRot).Rotator());
FQuat axisRot(FVector::UpVector, FMath::DegreesToRadians(90);
SetActorRotation((axisRot * GetActorRotation().Quaternion()).Rotator());
FMatrix(旋转矩阵)
旋转矩阵的源码如下
class FRotationMatrix
: public FRotationTranslationMatrix : public FMatrix
{
FRotationMatrix(const FRotator &Rot)
: FRotationTranslationMatrix(Rot, FVector::ZeroVector)
// FRotationTranslationMatrix(const FRotator& Rot, const FVector& Origin)
{
}
M[0][0] = CP * CY;
M[0][1] = CP * SY;
M[0][2] = SP;
M[0][3] = 0.f;
M[1][0] = SR * SP * CY - CR * SY;
M[1][1] = SR * SP * SY + CR * CY;
M[1][2] = -SR * CP;
M[1][3] = 0.f;
M[2][0] = -(CR * SP * CY + SR * SY);
M[2][1] = CY * SR - CR * SP * SY;
M[2][2] = CR * CP;
M[2][3] = 0.f;
M[3][0] = 0;
M[3][1] = 0;
M[3][2] = 0;
M[3][3] = 1.f;
}
实例 1
首先根据给轴(XZ)构造旋转矩阵,然后依据该旋转矩阵获取欧拉角,接着旋转并面向 targer。
注意,输入的轴应该提前进行归一化
FVector toFollow = target->GetActorLocation() - GetOwner()->GetActorLocation();
FMatrix rotationMatrix = FRotationMatrix::MakeFromXZ(toFollow, GetOwner()->GetActorUpVector());
GetOwner()->SetActorRotation(rotationMatrix.Rotator());
实例 2
根据任意两个方向向量获取欧拉角
FRotator rotation = FRotationMatrix::MakeFromXZ(dir, up).Rotator();
FRotator rotation = FRotationMatrix::MakeFromXY(dir, right).Rotator();
FRotator rotation = FRotationMatrix::MakeFromYZ(right,up).Rotator();