I used FVector::Dist instead of .Size()

I decided to use vector math to find the distance to the target and calculate whether or not the actor has reached the destination.

I also in the if statement show a NearZero() because when working with floats its nearly impossible to get an exact 0.

I also decided to have some other bool variables to help navigate the switching and the movement types. btw MyVector in this instance is the Location of the actor.

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

	//vital for getting actor + movement to share the same information
	if (HasAuthority()) {
		SetReplicates(true);
		SetReplicateMovement(true);
	}

	MyVector = GetActorLocation();
	StartLoc = GetTransform().TransformPosition(StartLocation);
	EndLoc = GetTransform().TransformPosition(TargetLocation);
	GlobalTargetLocation = EndLoc;
	bIsReturning = false;
}

void AMovingPlatform::Tick(float DeltaTime)
{
	if (HasAuthority()) {
		if (bIsMoveToLocation) 
		{
			FVector Direction = (GlobalTargetLocation - MyVector).GetSafeNormal();
			MyVector += Speed * DeltaTime * Direction;
			ShouldChangeDirection(MyVector, GlobalTargetLocation);
		}
		else {
			MyVector += PlatformVelocity * DeltaTime;
		}	
		SetActorLocation(MyVector);
	}
}

void AMovingPlatform::ShouldChangeDirection(FVector Start, FVector End)
{
	float DistanceToTarget = FVector::Dist(Start, End);
	//UE_LOG(LogTemp, Warning, TEXT("Distance to target: %f"), DistanceToTarget);
	if (DistanceToTarget <= 0.5) {
		if (bIsReturning) {
			GlobalTargetLocation = StartLoc;
		}
		else {
			GlobalTargetLocation = EndLoc;
		}
		bIsReturning = !bIsReturning;
	}
}
1 Like

Privacy & Terms