使用UE4中的差值创建一个可以平滑移动的平台
- 创建一个C++命名:FloatingPlatform,自动生成的类:AFloatingPlatform
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "FloatingPlatform.generated.h"
UCLASS()
class FIRSTPROJECT_API AFloatingPlatform : public AActor {
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AFloatingPlatform();
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Platform")
class UStaticMeshComponent* mess;
UPROPERTY(EditAnywhere)
FVector startPoint = FVector(0.0);
UPROPERTY(EditAnywhere, meta = (MakeEditWidget = "true"))
FVector endPoint = FVector(0.0);
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Platform")
float interpSpeed = 2.0;
FTimerHandle interpTimer;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Platform")
bool bIsInterp = false;
float distance = 0.0;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void troggleInterp();
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "FloatingPlatform.h"
// Sets default values
AFloatingPlatform::AFloatingPlatform() {
// 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;
mess = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("mess"));
RootComponent = mess;
}
// Called when the game starts or when spawned
void AFloatingPlatform::BeginPlay() {
Super::BeginPlay();
startPoint = GetActorLocation();
endPoint += startPoint;
GetWorldTimerManager().SetTimer(interpTimer, this, &AFloatingPlatform::troggleInterp, 1.0);
distance = (endPoint - startPoint).Size();
}
// Called every frame
void AFloatingPlatform::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
FVector currentLocation = GetActorLocation();
FVector iterp = FMath::VInterpTo(currentLocation, endPoint, DeltaTime, interpSpeed);
SetActorLocation(iterp);
if ((currentLocation - endPoint).Size() < 0.1){
FVector tempPoint = startPoint;
startPoint = endPoint;
endPoint = tempPoint;
}
}
void AFloatingPlatform::troggleInterp() {
bIsInterp = !bIsInterp;
}
- 创建对应的蓝图类,并且选中一个平台
- 把平台拖动到场景中,运行即可