keywords：Math, 线性代数, 旋转矩阵,相乘, Linear Algebra, Rotation Matrix, Multiply

##### 概述

``````FRotator Rot1(0.f, 90.f, 0.f);
FRotator Rot2(90.f,0.f, 0.f);
FRotator Result = Rot1 + Rot2;
``````

UE4

``````FRotator Rot1(0.f, 90.f, 0.f);
FRotator Rot2(90.f,0.f, 0.f);
FRotator Result = (FRotationMatrix(Rot1) * FRotationMatrix(Rot2)).Rotator();
``````

Unity 方式1：

``````Quaternion Rot1 = Quaternion.Euler(0, 0, 90);
Quaternion Rot2 = Quaternion.Euler(90, 0, 0);
Quaternion RotNew = Rot1 * Rot2;
Vector3 Result = RotNew.eulerAngles;
``````

Unity 方式2：

``````Quaternion Rot1 = Quaternion.Euler(0, 0, 90);
Quaternion Rot2 = Quaternion.Euler(90, 0, 0);
Matrix4x4 Mat = Matrix4x4.Rotate(Rot1) * Matrix4x4.Rotate(Rot2);
Vector3 Result = Mat.MultiplyVector(Vector3.forward);
``````

##### 实际应用：

``````(FRotationMatrix(Rr) * FRotationMatrix(Rw)).Rotator()
``````

UE4:

``````FRotator AMyPlayerController::GetInputRotationInWorld()
{
FRotator Ret = FRotator::ZeroRotator;
if (AMyCharacter* Player = Cast<AMyCharacter>(GetPawn()))
{
if(UCameraComponent* CameraComp = Player->GetFollowCamera())
{
FRotator InputRotLS = FVector(ForwardInputValue, RighInputInputValue, 0.f).Rotation();
FRotator CameraRotWS = FRotator(0.f, CameraComp->GetComponentRotation().Yaw, 0.f);
Ret = (FRotationMatrix(InputRotLS) * FRotationMatrix(CameraRotWS)).Rotator();
}
}

return Ret;
}
``````

Unity:

``````public void FixedUpdate()
{
if (variableJoystick.Horizontal == 0f && variableJoystick.Vertical == 0f)
{
return;
}

Vector3 DireLS = new Vector3(variableJoystick.Horizontal, 0f, variableJoystick.Vertical);
Quaternion RotLS = Quaternion.LookRotation(DireLS, Vector3.up);

//TestObj为临时测试对象，用于复制Camera的Transform，因为unity不支持new Transform()。
Transform CamRotWS = TestObj.transform;
Transform TraWS = CameraComp.transform;
CamRotWS.localPosition = TraWS.localPosition;
CamRotWS.position = TraWS.position;
CamRotWS.localRotation = TraWS.localRotation;
CamRotWS.rotation = TraWS.localRotation;
CamRotWS.localScale = TraWS.localScale;
//如果不是飞行类游戏，需要将Camera Rotation的Roll和Pitch清零，因为此时只需要Yaw
CamRotWS.localEulerAngles = new Vector3(0, CamRotWS.localEulerAngles.y, 0);

Matrix4x4 RotLSMat = Matrix4x4.Rotate(RotLS);
Matrix4x4 RotWSMat = Matrix4x4.Rotate(CamRotWS.localRotation);
Matrix4x4 MoveDirectionMat = RotLSMat * RotWSMat;

Vector3 MoveDirection = MoveDirectionMat.MultiplyVector(Vector3.forward);
rb.AddForce(MoveDirection * speed * Time.fixedDeltaTime, ForceMode.VelocityChange);
}
``````
##### Video Tutorials

Linear transformations and matrices | Essence of linear algebra, chapter 3
`风起于青萍之末，浪成于微澜之间。 ----先秦·宋玉 《风赋》`