Much more efficient code: Unreal Mulitplayer Master Lesson Sending Platform Back

Saw some great and efficient code snippets here in the comments plus some tweeks of my own.

My Variables from .h:

public:
	ASM_MovingPlatform();

	virtual void BeginPlay() override;
protected:
	virtual void Tick(float DeltaTime) override;

private:
	UPROPERTY(EditAnywhere, meta = (AllowPrivateAccess = "true"))
	float MoveSpeed = 10.f;
	UPROPERTY(EditAnywhere, meta = (MakeEditWidget = true, AllowPrivateAccess = "true"))
	FVector EndLocation;
	FVector BeginLocation;
	FVector MoveDirection;
	float MoveDistance;

My .cpp:

void ASM_MovingPlatform::BeginPlay()
{
	Super::BeginPlay();
	if (HasAuthority())
	{
		SetReplicates(true);
		SetReplicateMovement(true);
	}
	BeginLocation = GetActorLocation();   // Global Start
	EndLocation = GetTransform().TransformPosition(EndLocation);  // Global End
	MoveDirection = (EndLocation-BeginLocation).GetSafeNormal();  // Direction to Move
	MoveDistance = FVector::Dist(EndLocation, BeginLocation);  // Distance to Move
}

void ASM_MovingPlatform::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (HasAuthority())
	{
		FVector CurrentLocation = GetActorLocation();  // Find where the actor is at this tick
		if (FVector::Dist(BeginLocation, CurrentLocation) >= MoveDistance)
		{
			Swap(BeginLocation, EndLocation); // Swap begin and end points
			MoveDirection *= -1; // Change Direction
		}
		else
		{
			SetActorLocation(CurrentLocation + (MoveDirection * MoveSpeed * DeltaTime));
		}
	}
}
4 Likes

Great C++ code!

1 Like

Privacy & Terms