这一篇介绍一下Chatacter类中的按键绑定,通过按键可以让角色进行前后左右移动,上下左右观看,空格键跳跃,C键蹲下等。
项目设置:
按键的绑定,有轴映射和按键映射,轴映射是将键盘、鼠标或者摇杆等映射到一个名称,再和游戏进行绑定,进而控制角色移动;按键映射是对角色某种行为的短暂控制,例如按下空格键跳跃,松开停止跳跃等。
character类中的模型、弹簧臂、摄像机实例化,参数设置代码:
.h文件
private:
//弹簧臂组件
UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "Components",meta= (AllowPrivateAccess = "true"))
USpringArmComponent* SpringArm;
//摄像机组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true"))
UCameraComponent* CameraComp;
protected:
void MoveForward(float Value);
void MoveRight(float Value);
void BeginCrouch();
void EndCrouch();
.cpp文件
//为角色设置模型并设置相对位置和旋转
static ConstructorHelpers::FObjectFinder SkeletalMesh(TEXT("SkeletalMesh'/Game/Res/AnimStarterPack/UE4_Mannequin/Mesh/SK_Mannequin.SK_Mannequin'"));
if (SkeletalMesh.Succeeded())
{
GetMesh()->SkeletalMesh = SkeletalMesh.Object;
GetMesh()->SetRelativeLocation(FVector(0.0f,0.0f,-88.0f));
GetMesh()->SetRelativeRotation(FRotator(0.0f,-90.0f,0.0f));
}
//弹簧臂组件实例创建并初始化一些参数
SpringArm = CreateDefaultSubobject(TEXT("SpringArm"));
SpringArm->SetupAttachment(GetRootComponent());
SpringArm->TargetArmLength = 300.0f;
SpringArm->SetRelativeLocation(FVector(0.0f,0.0f,80.0f));
SpringArm->bUsePawnControlRotation = true;
//摄像机组件实例创建并初始化一些参数
CameraComp = CreateDefaultSubobject(TEXT("CameraComp"));
CameraComp->SetupAttachment(SpringArm);
//设置角色是否能够蹲起
GetMovementComponent()->GetNavAgentPropertiesRef().bCanCrouch = true;
设置角色蹲起要注意角色行走组件的是否能够蹲起的设置要开启,否则不会有效果。
绑定方法:
//左右走
PlayerInputComponent->BindAxis("MoveForward",this,&ASGCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight",this,&ASGCharacter::MoveRight);
//上下左右看
PlayerInputComponent->BindAxis("LookUp",this,&ASGCharacter::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookRight",this,&ASGCharacter::AddControllerYawInput);
//蹲下起立
PlayerInputComponent->BindAction("Crouch",IE_Pressed,this,&ASGCharacter::BeginCrouch);
PlayerInputComponent->BindAction("Crouch",IE_Released,this,&ASGCharacter::EndCrouch);
//跳跃
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ASGCharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ASGCharacter::StopJumping);
对应方法实现:
void ASGCharacter::MoveForward(float Value)
{
if (Value == 0.0f)
{
return;
}
AddMovementInput(GetActorForwardVector(),Value);
}
void ASGCharacter::MoveRight(float Value)
{
if (Value == 0.0f)
{
return;
}
AddMovementInput(GetActorRightVector(), Value);
}
void ASGCharacter::BeginCrouch()
{
Crouch();
}
void ASGCharacter::EndCrouch()
{
UnCrouch();
}
蹲下的方法绑定不能直接使用ASGCharacter::Crouch,vs会提示没有直接重载的方法。
最后的效果:
测试在场景中能够移动。