Different approach using `GetDirectionUnitVector`

I had a very similar approach to tackle this as the instructor, but I was computing unit direction vectors based on the current location to the global target location compared to the unit direction vector of the global start location to the global target location. The comparison will know it’s time to switch direction because the unit direction vector of current location to the global target location will “flip” and no longer match the unit direction vector of the global start location to the global target location after the platform moves past the global target location.

I also just negate the TargetLocation vector when it’s time to switch, which may be a bit less elegant than the instructor’s approach.

My code:

        FVector CurrentLocation = GetActorLocation();

        // Get unit direction to target
        FVector GlobalUnitDirection = UKismetMathLibrary::GetDirectionUnitVector(GlobalStartLocation, GlobalTargetLocation);
        FVector CurrentUnitDirection = UKismetMathLibrary::GetDirectionUnitVector(CurrentLocation, GlobalTargetLocation);

        if (!GlobalUnitDirection.Equals(CurrentUnitDirection))
        {
            FVector Swap = GlobalStartLocation;
            GlobalStartLocation = GlobalTargetLocation;
            GlobalTargetLocation = Swap;
            TargetLocation = -(TargetLocation);
        }

        FVector NewLocation = FMath::VInterpConstantTo(CurrentLocation, CurrentLocation+TargetLocation, DeltaTime, Speed);
        SetActorLocation(NewLocation);

Note that this will require the including of the KismetMathLibrary:
#include "Kismet/KismetMathLibrary.h"

1 Like

Privacy & Terms