Tick() to move platform to Target Location

I realized that the target location, as it is relative offset to the platform location, when normalized can be used directly to add to the platform’s location.

void AMovingPlatform::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (HasAuthority()) // If Running on server
	{
		FVector DistanceOffset = TargetLocation.GetSafeNormal() * Speed * DeltaTime;
		SetActorLocation(GetActorLocation() + DistanceOffset);
	}
}

But this may cause a problem later when you actually want to stop at the target location because you need that world position.

So this was my final code to move the platform to the target location and stop. In BeginPlay store the TargetLocation and StartPosition (will need this later).

void AMovingPlatform::BeginPlay()
{
	Super::BeginPlay();

	if (HasAuthority())
	{
		// Replicate this actor to the clients
		SetReplicates(true);
		SetReplicateMovement(true);
	}

	StartLocation = GetActorLocation();
	WorldTargetLocation = GetTransform().TransformPosition(TargetLocation);
}

// Called every frame
void AMovingPlatform::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (HasAuthority()) // If Running on server
	{
		FVector Location = GetActorLocation();
		if (!(Location - WorldTargetLocation).IsNearlyZero(5.0f))
		{
			FVector DistanceOffset = TargetLocation.GetSafeNormal() * Speed * DeltaTime;
			SetActorLocation(Location + DistanceOffset );
		}
	}
}
1 Like

It will cause some issues but a little adjustment will work. The target as a variable gets around this and so when it reaches one location, you change the target to the next location.
Theoretically you could have a collection of locations and move in a loop around them or bounce.
It depends on how complicated you want to make it.

1 Like

Privacy & Terms