UE4 C++学习笔记之控制Pawn做前后左右移动

任务:控制场景中的Pawn做前后左右移动

步骤一、在项目设置---输入中,建立相应的轴映射

第二步、修改C++ Pawn类Creature的相关代码

Creature.h部分关键代码如下:

public:

        //最大移动速度
	UPROPERTY(EditAnywhere)
	float MaxSpeed;

        //当前移动速度
	UPROPERTY(VisibleInstanceOnly)
	FVector CurrentVelocity;

private:

        //前后位移函数
	void MoveForward(float Value);
        //左右位移函数
	void MoveRight(float Value);

Creature.cpp部分关键代码如下:

ACreature::ACreature()
{
 	// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
	StaticMesh->SetupAttachment(GetRootComponent());
	Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
	Camera->SetupAttachment(GetRootComponent());
	Camera->SetRelativeLocation(FVector(-300, 0, 300));
	Camera->SetRelativeRotation(FRotator(-45, 0, 0));

        //初始化最大移动速度和当前移动速度
	MaxSpeed = 300;
	CurrentVelocity = FVector(0);

	// 将该pawn设为由最小编号玩家控制
	AutoPossessPlayer = EAutoReceiveInput::Player0;
}
void ACreature::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

        //虚幻引擎自带函数库,将轴映射获取的值与MoveForward等函数中的Value值关联起来
	PlayerInputComponent->BindAxis("MoveForward", this, &ACreature::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &ACreature::MoveRight);
}


        //根据获取的轴映射的值和MaxSpeed,更新CurrentVelocity向量
void ACreature::MoveForward(float Value)
{
	CurrentVelocity.X = FMath::Clamp(Value, -1.f, 1.f) * MaxSpeed;
}

void ACreature::MoveRight(float Value)
{
	CurrentVelocity.Y = FMath::Clamp(Value, -1.f, 1.f) * MaxSpeed;
}
//逐帧运行,根据当前的CurrentVelocity对当前对象进行位移运算,达到控制移动的效果
void ACreature::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	FVector NowLocation = GetActorLocation() + CurrentVelocity * DeltaTime;
	SetActorLocation(NowLocation);
}

 


版权声明:本文为weixin_44928892原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。