UE - 控制器、角色与相机的转向
控制器输入以旋转视角
创建完Character后,添加SpringArm组件、Camera组件,然后设置SpringArmComponent上CameraSetting上的 Use Pawn Control Rotation

再配合代码绑定轴输入
void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight);
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
}
void APlayerCharacter::MoveForward(float AxisValue)
{
if ((Controller != nullptr) && (AxisValue != 0.0f))
{
// 找出向前方向
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// 获取向前矢量
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
// 添加该方向动作
AddMovementInput(Direction, AxisValue);
}
}
void APlayerCharacter::MoveRight(float AxisValue)
{
if ((Controller != nullptr) && (AxisValue != 0.0f))
{
// 找出向右方向
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// 获取向右矢量
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// 添加该方向动作
AddMovementInput(Direction, AxisValue);
}
}

最终就能实现 控制器旋转SpringArm 及基础的角色移动:

Use Controller Rotaion Yaw、Use Controller Desired Rotation 与 Orient Rotation to Movement
基于上文创建完Character,然后就需要处理 控制器与Character朝向问题,涉及的核心的设置参数有3个:
- Pawn上的 Use Controller Rotaion Yaw
- CharacterMoveComponent上的 Use Controller Desired Rotation 和 Orient Rotation to Movement


Use Controller Rotaion Yaw
作用是 时刻保持 Pawn在Yaw轴朝向与控制器一致。常用于 FPS类游戏
当 Use Controller Rotaion Yaw = true,进行 左右旋转视角、角色向前移动、角色向后移动 表现示例:

Use Controller Desired Rotation
作用是 以一定速率平滑过渡 旋转Pawn的朝向与控制器一致,可以说跟上文 Use Controller Rotaion Yaw 区别只在于 是否平滑过渡
当 Use Controller Desired Rotation = true,进行 左右旋转视角、角色向前移动、角色向后移动 表现示例:
(注意 此情况下角色后移 不会改变Pawn朝向)

Orient Rotation to Movement
作用是 在上文 Use Controller Desired Rotation 效果基础上 旋转Pawn朝向移动方向,常用于 常规RPG类游戏
当 Orient Rotation to Movement = true,进行 左右旋转视角、角色向前移动、角色向后移动 表现示例:
(注意 此情况下角色后移 会改变Pawn朝向,左右移动也是)

总结
参数覆盖优先级为:Use Controller Rotaion Yaw -> Orient Rotation to Movement -> Use Controller Desired Rotation
参数选择思路:
- FPS类(需要角色时刻朝向前方的):设置 Pawn上的 Use Controller Rotaion Yaw
- RPG类:
2.1 需要角色在移动时改变自身朝向的:设置 CharacterMoveComponent上的 Orient Rotation to Movement
2.2 角色能移动但需要自身始终面朝前的:设置 CharacterMoveComponent上的 Use Controller Desired Rotation

浙公网安备 33010602011771号