虚幻4—C++笔记—第三人称视角人物设计及源码分析

1,973 阅读2分钟

「这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

源码之下,了无秘密。——侯捷

1、创建一个C++工程

  • 创建C++类,继承于ACharacter,命名为ThirdCharacter

2、ThirdCharacter.h分析

  • 创建摄像机手臂组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class USpringArmComponent* ArmCamera;

VisibleAnywhere,BlueprintReadOnly蓝图仅可读。类型为Camera

  • 创建摄像机组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class UCameraComponent *FallowCamera;
  • 前进后退函数
UFUNCTION(BlueprintCallable)
		void MoveForward(float Value);
  • 左右移动函数
UFUNCTION(BlueprintCallable)
		void MoveRight(float Value);

3、ThirdCharacter.cpp分析

  • 设置胶囊体初始半径于高度
GetCapsuleComponent()->SetCapsuleSize(Radius, Height);

注意默认碰撞判定为胶囊体

  • 不让输入控制器控制胶囊体的Rotation,让输入控制只影响摄像机
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
  • 设置角色移动

    • 让角色旋转到指定方向再移动

      GetCharacterMovement()->bOrientRotationToMovement = true;
      
    • 设置胶囊体旋转速度

      GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f);
      
    • 跳跃z轴高度

      GetCharacterMovement()->JumpZVelocity = 450.f;
      
    • 空中控制,坠落时,角色可用的横向移动控制量。0 = 无控制,1 = 在 MaxWalkSpeed 的最大速度下完全控制。

      GetCharacterMovement()->AirControl = 0.2f;
      
  • 创建一个相机手臂(如果发生碰撞,则向玩家拉入)

    ArmCamera = CreateDefaultSubobject<USpringArmComponent>(TEXT("ArmCamera"));
    ArmCamera->SetupAttachment(RootComponent);
    
  • 设置摄像机在角色身后的距离

    ArmCamera->TargetArmLength = 300.0f;
    
  • 相机手臂基于控制器旋转

    ArmCamera->bUsePawnControlRotation = true;
    
  • 创建一个摄像机

FallowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
  • 将相机连接到吊杆末端

    FallowCamera->SetupAttachment(ArmCamera, USpringArmComponent::SocketName);
    
  • 相机不相对于手臂旋转

    FallowCamera->bUsePawnControlRotation = false;
    
  • 绑定按键等基本操作

  • Jump,IE_Pressed绑定到ACharacter::Jump,IE_Released绑定到ACharacter::StopJumping

  • MoveForward,绑定到AThirdCharacter::MoveForward

  • MoveRight,绑定到AThirdCharacter::MoveRight

  • Turn,绑定到APawn::AddControllerYawInput,AThirdCharacter继承于ACharacterACharacter继承于APawn

  • LookUp,绑定到APawn::AddControllerPitchInputAThirdCharacter继承于ACharacterACharacter继承于APawn

  • MoveForward函数编写,我感觉函数功能是获取当前摄像机视角下,去旋转人物的x轴与当前视角x轴一致

void AThirdCharacter::MoveForward(float Value)
{
	const FRotator Rotation = Controller->GetControlRotation();
	const FRotator YawRotation(0, Rotation.Yaw, 0);

	// get forward vector
	const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);//我感觉功能是获取当前摄像机视角下,
																				//去旋转人物的x轴与当前视角x轴一致
	AddMovementInput(Direction, Value);
}

大佬可以详细讲下FRotationMatrix此函数作用吗?欢迎评论

4、UE4绑定键盘

5、设置胶囊体人物骨架静态网格,并设置动画

素材为帕拉共素材,动画蓝图为自己根据素材动画设计