Skip to content

Instantly share code, notes, and snippets.

@Riztazz
Created December 19, 2021 07:06
Show Gist options
  • Save Riztazz/2e91504fd68b3eac15ddc5b624cceef9 to your computer and use it in GitHub Desktop.
Save Riztazz/2e91504fd68b3eac15ddc5b624cceef9 to your computer and use it in GitHub Desktop.
Compute rotation and translation to target location with given distance percentage in UnrealEngine 5
// originLoc - whos position we want to compute from
// targetLoc - what is our target position (ie. objects victim)
// distanceMod - distance between origin and target that we want to cover. 0 - 1.f where 1f is 100%
// TranslationResult - computed result, example usage: ...GetController()->SetClientLocation( TranslationResult, {} );
// RotationResult - computed rotation to targetl ocation, usage: ...GetController()->SetClientRotation( RotationResult );
// Move actor and face computed rotation, GetController()->SetClientLocation(TranslationResult, RotationResult);
// note that RotationResult is not recalculated and it might be a different after move
// if you want updated rotation, use this part to calculate new rotation
// FRotator rotationToTarget = UKismetMathLibrary::MakeRotFromXZ( Forward, FVector::UpVector );
// where Forward is ( TranslationResult - targetLocation )
void GetRotatedLocationTowards( FVector const& originLoc, FVector const& targetLoc, FVector& TranslationResult, FRotator& RotationResult,
float distanceMod = 1.f )
{
FVector Forward = targetLoc - originLoc;
float dist = FVector::Dist( targetLoc, originLoc ) * distanceMod;
FRotator rotationToTarget = UKismetMathLibrary::MakeRotFromXZ( Forward, FVector::UpVector );
FVector forwardVecFromLook = UKismetMathLibrary::GetForwardVector( rotationToTarget );
FVector computedLocation = originLoc + ( forwardVecFromLook * dist );
TranslationResult = computedLocation;
RotationResult = rotationToTarget;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment