Solution using FMath::Lerp

In MovingPlatform.h

....
protected:
	FVector WorldStartLocation;
	FVector WorldEndLocation;
	float LerpAlpha = 0.0f;
	float LerpStep = 0.0f;
...

In MovingPlatform.cpp

...
void AMovingPlatform::BeginPlay()
{
	Super::BeginPlay();
	if (HasAuthority()) {
		SetReplicates(true);
		SetReplicateMovement(true);
		WorldStartLocation = GetActorLocation();
		WorldEndLocation = WorldStartLocation + TargetLocation;
		FVector Distance = WorldEndLocation - WorldStartLocation;
		LerpAlpha = 0;
		LerpStep = MovementSpeed/Distance.Size();
	}
}

void AMovingPlatform::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (HasAuthority()) {
		LerpAlpha += LerpStep*DeltaTime;
		SetActorLocation(FMath::Lerp(WorldStartLocation, WorldEndLocation, LerpAlpha));
		if (LerpStep > 0 && LerpAlpha >= 1 || LerpStep < 0 && LerpAlpha <= 0) {
			LerpStep *= -1;
		}
	}
}
1 Like

A few comments (for future readers):

  • You’re not transforming the target location
  • If the target location is the same as the start location, you have a division-by-0 error when computing LerpStep
  • I would use FMath::Clamp on LerpAlpha before computing the new location, so that the platform never moves beyond the endpoints
  • Once LerpAlpha is clamped, I would remove the now-unnecessary checks for LerpStep >0,<0 (since LerpAlpha is guaranteed to be 0 or 1 at the extremes, it’s guaranteed to be those values only for one frame, i.e. it won’t flip-flop like yours could otherwise if you’re unlucky with DeltaTime),
1 Like

Privacy & Terms