The original tutorial is based on UE 4.18, I am based on UE 4.25.

English original Address

The following tutorial creates a new C++ Actor subclass and names it FloatingActor. Four floating point variables will be created in the header file. We will create RunningTime, XValue, YValue, and ZValue variables.

Here is the final header code

FloatingActor.h

#pragma once

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

UCLASS(a)class UNREALCPP_API AFloatingActor : public AActor
{
	GENERATED_BODY(a)public:	
	// Sets default values for this actor's properties
	AFloatingActor(a);protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay(a) override;

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

	// declare our float variables 
	float RunningTime;
	
	UPROPERTY(EditAnywhere, Category = Movement)
	float XValue;

	UPROPERTY(EditAnywhere, Category = Movement)
	float YValue;

	UPROPERTY(EditAnywhere, Category = Movement)
	float ZValue;
	
	
};
Copy the code

Next, we will put all the logic into the Tick function. First, let’s declare a variable equal to the actor’s current location for each frame using GetActorLocation. This will allow us to change the X, Y, and Z values of the actor and move around the scene. To smooth the motion, we’ll use FMath:Sin to set our DeltaHeight variable.

float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
Copy the code

Next, we’ll get the X, Y, and Z coordinates of the actor location and add DeltaTIme * Value. In the header file, we made the variables editable anywhere, so in the editor we could easily adjust the amount and direction of character movement. Next, set RunningTime to DeltaHeight. Finally, set the location of actor to NewLocation.

The following is. The final version of CPP.

FloatingActor.cpp

#include "FloatingActor.h"


// Sets default values
AFloatingActor::AFloatingActor()
{
 	// 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;

}

// Called when the game starts or when spawned
void AFloatingActor::BeginPlay(a)
{
	Super::BeginPlay(a); }// Called every frame
void AFloatingActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// on every frame change location for a smooth floating actor
	FVector NewLocation = GetActorLocation(a);float DeltaHeight = (FMath::Sin(RunningTime + DeltaTime) - FMath::Sin(RunningTime));
	NewLocation.X += DeltaHeight *  XValue;
	NewLocation.Y += DeltaHeight *  YValue;
	NewLocation.Z += DeltaHeight *  ZValue;

	RunningTime += DeltaTime;
	SetActorLocation(NewLocation);

}
Copy the code

After the operation, the effect picture is as follows