FVector::Distance() instead of magnitude

In this lesson, when I was working this on my own, I looked up the FVector API and found FVector::Distance(). I used this in my code rather than Magnitude as shown… is there any reason we couldn’t use this function for the purposes of moving the platform?
My current code that uses this:

void AMovingPlatform::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    
    if(HasAuthority()){
        FVector CurrentLocation = GetActorLocation();
        if(FVector::Distance(CurrentLocation, GlobalStartLocation) > FVector::Distance(GlobalTargetLocation, GlobalStartLocation))
        {
            FVector Holder = GlobalStartLocation;
            GlobalStartLocation = GlobalTargetLocation;
            GlobalTargetLocation = Holder;
        }
        FVector Direction = (GlobalTargetLocation - GlobalStartLocation).GetSafeNormal();
        CurrentLocation += Direction * DeltaTime * PlatformSpeed;
        SetActorLocation(CurrentLocation);
    }
}

No, that looks great!

Nice! I did something similar but I put my Direction inside of BeginPlay.

    PlatformStartLocation = GetActorLocation();
    TargetStartLocation = GetTransform().TransformPosition(TargetLocation);
    Direction = (TargetStartLocation - PlatformStartLocation).GetSafeNormal();

Then I flip the Direction when going back and forth inside of Tick.

    FVector PlatformLocation = GetActorLocation();
    	
    if(FVector::Dist(PlatformLocation, TargetStartLocation) <= 1 || 
        FVector::Dist(PlatformLocation, PlatformStartLocation) <= 1) 
        Direction *= -1;
     
    PlatformLocation += Speed * DeltaTime * Direction;
    SetActorLocation(PlatformLocation);

I used FVector::DistSquared instead of FVector::Dist, and calculated the initial distance in BeginPlay as well. DistSquared is a bit more efficient since it can skip the square root, which doesn’t really matter in this case but is something to keep in mind IF this code were to run at a high frequency.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms