首先基于Character创建一个角色类,在头文件为其添加弹簧臂和摄像机组件
1 2 3 4
| UPROPERTY(VisibleAnywhere, Category = "Comp") class UCameraComponent* CameraComp; UPROPERTY(VisibleAnywhere, Category = "Comp") class USpringArmComponent* SpringComp;
|
在构造函数中将相关组件创建出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include "Camera/CameraComponent.h" #include "GameFramework/SpringArmComponent.h" #include "GameFramework/CharacterMovementComponent.h" CameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp")); SpringComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringComp")); SpringComp->SetupAttachment(RootComponent); CameraComp->SetupAttachment(SpringComp); SpringComp->bUsePawnControlRotation = true; CameraComp->bUsePawnControlRotation = true; bUseControllerRotationRoll = false; bUseControllerRotationYaw = false; bUseControllerRotationPitch = false; GetCharacterMovement()->bOrientRotationToMovement = true;
|
回到角色类头文件中,申明所需的移动、视角旋转函数
1 2 3 4
| void MoveForward(float value); void MoveRight(float value); void Turn(float value); void LookUp(float value);
|
实现移动、视角旋转函数,并且绑定输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| void APCharacter::MoveForward(float value) { if (Controller != NULL && value != 0) { const FRotator ControllerRotator = Controller->GetControlRotation(); const FRotator YawRotator(0.f, ControllerRotator.Yaw, 0.f); const FVector Direction = FRotationMatrix(YawRotator).GetUnitAxis(EAxis::X); AddMovementInput(Direction, value); } }
void APCharacter::MoveRight(float value) { if (Controller != NULL && value != 0) { const FRotator ControllerRotator = Controller->GetControlRotation(); const FRotator YawRotator(0.f, ControllerRotator.Yaw, 0.f); const FVector Direction = FRotationMatrix(YawRotator).GetUnitAxis(EAxis::Y); AddMovementInput(Direction, value); } }
void APCharacter::Turn(float value) { if (Controller != NULL && value != 0) { AddControllerYawInput(value); } }
void APCharacter::LookUp(float value) { if (Controller != NULL && value != 0) { AddControllerPitchInput(value); } }
void APCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &APCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &APCharacter::MoveRight); PlayerInputComponent->BindAxis("Turn", this, &APCharacter::Turn); PlayerInputComponent->BindAxis("LookUp", this, &APCharacter::LookUp); }
|
回到虚幻编辑器中,在项目设置中添加,相关的操作映射
Axis Mappings
MoveForward
W Scale 1.0
S Scale -1.0
MoveRight
D Scale 1.0
A Scale -1.0
Turn
Mouse X Scale 1.0
LookUp
Mouse Y Scale -1.0
再创建一个相关蓝图类,将模型与动画蓝图设置上就完成了