角色移动

181 阅读2分钟

写在前面

在完成角色的创建后,接下来我们进行角色的移动的绑定,一共有两种移动:

  • 角色自身的前后左右移动
  • 视口的移动

Input Binding

首先我们先建立键盘输入绑定:Project Setting -> Input

image.png

MouseX代表的是左右滑动鼠标,MouseY代表前后滑动鼠标,我们将Mouse Y的Scale设为-1是为了后面在代码里好写向上抬头的函数。

书写函数


void ABlasterCharacter::SetupPlayerInputComponent(UInputComponent *PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	// 绑定输入事件
	PlayerInputComponent->BindAxis("MoveForward", this, &ABlasterCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &ABlasterCharacter::MoveRight);
	PlayerInputComponent->BindAxis("Turn", this, &ABlasterCharacter::Turn);
	PlayerInputComponent->BindAxis("LookUp", this, &ABlasterCharacter::LookUp);
	PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
}

// BlasterCharacter.cpp

void ABlasterCharacter::MoveForward(float Value)
{
	auto MyController = GetController();
	if (MyController && Value)
	{
		// 得到旋转器 (pitch, yaw, roll) 分别是绕着(y, z, x) 旋转
		auto YawRotator = FRotator(0, MyController->GetControlRotation().Yaw, 0);
		// 先得到,根据旋转器得到可以达到相同旋转效果的矩阵(因为我们只做了Yaw, 因此我们的角色相当于xy平面上绕原点旋转)
		// 这个矩阵的x轴 就是我们原坐标系旋转之后得到的x轴
		auto Direction = FVector(FRotationMatrix(YawRotator).GetUnitAxis(EAxis::X));

		AddMovementInput(Direction, Value);
	}
}

void ABlasterCharacter::MoveRight(float Value)
{
	auto MyController = GetController();
	if (MyController && Value)
	{
		// 得到旋转器 (pitch, yaw, roll) 分别是绕着(y, z, x) 旋转
		auto YawRotator = FRotator(0, MyController->GetControlRotation().Yaw, 0);
		// 先得到,根据旋转器得到可以达到相同旋转效果的矩阵(因为我们只做了Yaw, 因此我们的角色相当于xy平面上绕原点旋转)
		// 这个矩阵的x轴 就是我们原坐标系旋转之后得到的y轴
		auto Direction = FVector(FRotationMatrix(YawRotator).GetUnitAxis(EAxis::Y));

		// 这里的移动是角色实际的移动,而不是视角的移动
		AddMovementInput(Direction, Value);
	}
}

// 这里指的是左右朝向
void ABlasterCharacter::Turn(float Value)
{
	// 左右的旋转由 Yaw 决定, Controller Input是视角的旋转
	AddControllerYawInput(Value);
}

void ABlasterCharacter::LookUp(float Value)
{
	// 在Camera设置中打开 Use Pawn Control Rotation 才能正常工作
	AddControllerPitchInput(Value);
}