1.UEC++实现第三人称角色移动 + 视角框架

层级组件:
ASCharacter(继承ACharacter,自带胶囊体 + 骨骼网络 + 移动组件)
RootComponent = CapsuleComponent(胶囊体,ACharacter自动创建)
SpringArmComp 弹簧臂(挂载到胶囊体)
Camera 摄像机(挂载到弹簧臂)

1
2
3
4
5
SpringArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArmComp"));
SpringArmComp->SetupAttachment(RootComponent); // 弹簧臂挂胶囊体

CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
CameraComp->SetupAttachment(SpringArmComp); // 摄像机挂弹簧臂

弹簧臂的作用:当摄像机被墙挡住时能自动缩短
Pasted image 20260827195447.png

2.三个旋转开关

整个框架的核心,三个bool各管一件事情:

变量 当前值 职责
SpringArmComp->bUsePawnControlRotation true 弹簧臂跟随”控制器旋转” → 鼠标上下/左右转动视角
GetCharacterMovement()->bOrientRotationToMovement true 角色身体自动转向移动方向(脸朝走的方向)
bUseControllerRotationYaw false 角色身体不直接跟鼠标偏航转(防止”歪脖子/僵硬转”)
三者配合后的效果:
鼠标转动 → 只改变视角(弹簧臂跟着转)
角色移动 → 身体自动转向移动方向(面向走的方向)
视角与身体朝向互不干扰 → 第三人称标准手感

3.输入绑定(4个轴)

Pasted image 20260827195637.png
1
2
3
4
5
PlayerInputComponent->BindAxis("MoveForward", this, &ASCharacter::MoveForward); // W/S
PlayerInputComponent->BindAxis("MoveRight", this, &ASCharacter::MoveRight); // A/D
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); // 鼠标左右 → 改偏航
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); // 鼠标上下 → 改俯仰

Turn/LookUp 绑定的是 APawn 的内置函数,不需要自己实现(写个空函数即可) Pasted image 20260827195741.png

4.移动方向计算(相对计算机)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void ASCharacter::MoveForward(float Value)
{
FRotator ControlRot = GetControlRotation(); // 取视角朝向
ControlRot.Pitch = 0.0f; // 去掉抬头/低头
ControlRot.Roll = 0.0f; // 去掉歪头
AddMovementInput(ControlRot.Vector(), Value); // 沿视角水平前方走
}

void ASCharacter::MoveRight(float Value)
{
FRotator ControlRot = GetControlRotation();
ControlRot.Pitch = 0.0f;
ControlRot.Roll = 0.0f;
FVector RightVector = FRotationMatrix(ControlRot).GetUnitAxis(EAxis::Y); // 取"右"方向
AddMovementInput(RightVector, Value);
}

要点:
ControlRot.Vector() = 视角的前方向(Forward,X 轴)
FRotationMatrix(ControlRot).GetUnitAxis(EAxis::Y) = 视角的右方向(Y 轴)
清零 Pitch 后,移动方向始终平行于地面,不会钻地/飞天


本文从 LearnByCompany 原始文档 自动同步。