例,我在Test_002项目中给Battery类添加Mover组件。
从整体上,代码是这个样子:
Mover.h
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "Mover.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TEST_002_API UMover : public UActorComponent
{
GENERATED_BODY()
public:
UMover();
protected:
virtual void BeginPlay() override;
void OwnerMove(float DeltaTime) const;
public:
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
private:
UPROPERTY(EditAnywhere)
float MoveTime;
UPROPERTY(EditAnywhere)
FVector MoveOffset;
UPROPERTY(EditAnywhere)
bool bIsMoving;
FVector StartLocation;
};
Mover.cpp
#include "Component/Mover.h"
UMover::UMover()
{
PrimaryComponentTick.bCanEverTick = true;
MoveTime = 1.0f;
MoveOffset = FVector(100.0f, 100.0f, 100.0f);
bIsMoving = false;
}
void UMover::BeginPlay()
{
Super::BeginPlay();
StartLocation = GetOwner()->GetActorLocation();
bIsMoving = true;
}
void UMover::OwnerMove(const float DeltaTime) const
{
const FVector CurrentLocation = GetOwner()->GetActorLocation();
const FVector TargetLocation = StartLocation + MoveOffset;
const float Speed = FVector::Distance(CurrentLocation, TargetLocation) / MoveTime;
const FVector NewLocation = FMath::VInterpConstantTo(CurrentLocation, TargetLocation, DeltaTime, Speed);
GetOwner()->SetActorLocation(NewLocation);
}
void UMover::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
OwnerMove(DeltaTime);
}
Battery.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Battery.generated.h"
class UMover;
UCLASS()
class TEST_002_API ABattery : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ABattery();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
protected:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Battery")
UStaticMeshComponent* BatteryMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Battery")
UMover* Mover;
};
Battery.cpp
#include "Actor/Battery.h"
#include "Component/Mover.h"
ABattery::ABattery()
{
PrimaryActorTick.bCanEverTick = true;
BatteryMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BatteryMesh"));
RootComponent = BatteryMesh;
Mover = CreateDefaultSubobject<UMover>(TEXT("Mover"));
Mover->RegisterComponent();
}
void ABattery::BeginPlay()
{
Super::BeginPlay();
}
void ABattery::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}