Unreal Engine C++ :Character
1. 新建一个Character C++类
默认包含:
1 //构造函数 2 ATheCharacter(); 3 4 //开始 5 virtual void BeginPlay() override; 6 7 //更新 8 virtual void Tick(float DeltaTime) override; 9 10 //输入组件 11 virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
2. 绑定相机和弹簧臂
为了能正常看到玩家,需要绑定相机和弹簧臂,弹簧臂绑定在人物胶囊体上,相机绑定在弹簧臂上。
UPROPERTY(VisibleAnywhere) class USpringArmComponent* SpringArmComp; UPROPERTY(VisibleAnywhere) class UCameraComponent* CameraComp;
1 #include <GameFramework/SpringArmComponent.h> 2 #include <Camera/CameraComponent.h> 3 4 // Sets default values 5 ATheCharacter::ATheCharacter() 6 { 7 // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. 8 PrimaryActorTick.bCanEverTick = true; 9 10 SpringArmComp = CreateDefaultSubobject<USpringArmComponent>("SpringArmComp"); 11 SpringArmComp->SetupAttachment(RootComponent); 12 13 CameraComp = CreateDefaultSubobject<UCameraComponent>("CameraComp"); 14 CameraComp->SetupAttachment(SpringArmComp); 15 }
-------------------------------------------
transient property???
Property is transient, meaning it will not be saved or loaded.
Properties tagged this way will be zero-filled at load time.
SetupAttachment 和 AttachToComponent的区别?
都是场景组件的附加方法。前者在构造时调用,后者在游戏中调用。
3. 添加移动组件
然后让玩家可以前后左右走,转向
1 void ATheCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) 2 { 3 Super::SetupPlayerInputComponent(PlayerInputComponent); 4 5 PlayerInputComponent->BindAxis("MoveForward", this, &ATheCharacter::MoveForward); 6 PlayerInputComponent->BindAxis("MoveRight", this, &ATheCharacter::MoveRight); 7 PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); 8 PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); 9 }
void ATheCharacter::MoveForward(float value) { AddMovementInput(GetActorForwardVector(), value); } void ATheCharacter::MoveRight(float value) { AddMovementInput(GetActorRightVector(), value); }
别忘了头文件声明方法:
void MoveForward(float value); void MoveRight(float value);
--------------------------------------------
第一个参数是project settings里绑定的委托名
第三个参数是C++里要执行的委托函数
4. 角色旋转
UE是左手坐标系:
pitch也叫做俯仰角,绕绿色Y轴旋转
yaw也叫偏航角,绕蓝色Z轴旋转
roll也叫滚动角,绕红色X轴旋转
参考:区分ControllerRotation 和 ActorRotation
-------------------------------------------------------
到了这里,还有些小问题,比如人物左右跑是平移方式,而不会左右转之后再跑;虽然设置了LookUp但并未生效。
一、控制器控制旋转
LookUp:可以在角色蓝图里->弹簧臂->勾选 使用控制器控制旋转
或者在C++代码中控制这一选项:
SpringArmComp->bUsePawnControlRotation=true;
二、角色移动组件控制旋转
Character Movement->勾选 Orient Rotation to Movement
表示人物随加速度方向旋转
(取消弹簧臂里 Inherit Yaw 选框,这两项不能同时选,同时勾选生效的是控制器控制旋转)
等同于C++代码:
#include "GameFramework/CharacterMovementComponent.h" GetCharacterMovement()->bOrientRotationToMovement = true; bUseControllerRotationYaw = false;
Character Movement->Rotation Rate 控制旋转速率