UE4 C++学习笔记之浮动平台

任务:创建能在场景中按固定周期做上下浮动的Actor

以Actor为父类,新建C++类FloatPlatform

FloatPlamform.h代码如下:

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "FloatPlatform.generated.h"

UCLASS()
class LEARNTEST_API AFloatPlatform : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	AFloatPlatform();

	UPROPERTY(EditAnywhere)
	class UStaticMeshComponent* StaticMesh;

        //终点位置向量,可在细节面板中编辑
	UPROPERTY(EditAnywhere, meta = (MakeEditWidget = "true"))
	FVector EndPoint;
        
         //起点位置向量       
	UPROPERTY(EditAnywhere)
	FVector StartPoint;

        //定时器时延时间
	UPROPERTY(EditAnywhere)
	float DelayTime;

        //定时器句柄
	FTimerHandle Change;

        //声明函数:改变运动方向
	UFUNCTION()
	void ChangeDirection();

        //布尔变量:决定运动方向
	bool bDirection;

        //运动速度率
	UPROPERTY(EditAnywhere)
	float Speed;

        //间隔时间
	UPROPERTY(EditAnywhere)
	float IntervalTime;


protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

};

FloatPlatform.cpp代码如下:

#include "FloatPlatform.h"
#include "Components\StaticMeshComponent.h"
#include "Engine\Public\TimerManager.h"
#include "Math\UnrealMathUtility.h"

// Sets default values
AFloatPlatform::AFloatPlatform()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
	StaticMesh->SetupAttachment(RootComponent);

    //初始化变量
	Speed = 1;
	IntervalTime = 5;
	bDirection = true;

	DelayTime = 0;
}

//定义函数:改变运动方向
void AFloatPlatform::ChangeDirection()
{
	bDirection = !bDirection;
}

// Called when the game starts or when spawned
void AFloatPlatform::BeginPlay()
{
	Super::BeginPlay();
    
        //得到Actor的初始位置,将其赋值给StartPoint
	StartPoint = GetActorLocation();

        //通过StartPoint和细节面板中设置的EndPoint相加得到EndPoint
	EndPoint += StartPoint;

        //开启定时器,并开启循环和时延
	GetWorldTimerManager().SetTimer(Change, this,&AFloatPlatform::ChangeDirection, IntervalTime, true, DelayTime);
}

// Called every frame
void AFloatPlatform::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	FVector CurrentLocation = GetActorLocation();
	
	FVector NewLocation;
	if (bDirection)
	{
                //通过调用这个数学函数得到每一帧应该设置的位置以得到相对平滑的运动(这个函数的算法目前我还不理解)
                NewLocation = FMath::VInterpTo(CurrentLocation, EndPoint, DeltaTime, Speed);
	}
	else
	{
		NewLocation = FMath::VInterpTo(CurrentLocation, StartPoint, DeltaTime, Speed);
	}

	SetActorLocation(NewLocation);
}

猜你喜欢

转载自blog.csdn.net/weixin_44928892/article/details/108139113