• News

• Industries

• Learning & Support

• Community

• Marketplace

# "Closest Rotation" Function

Hello Lovelies,

I’m trying to make a function that will evaluate an array of rotations and see which is closest to another given rotation.

I envisage the function taking 2 arguments, the first a single rotation and the second an array of rotations to be compared to. The function would then return the index of the closest rotation in the array.

If anyone can help, that would be absolutely marvellous. Anything, even pseudo code would be magnificent.

Thanks,
James

Here is a way to do it :

.h

``````
int32 GetClosestRotationIndex(FRotator TargetRotation, const TArray<FRotator>& RotationsArray) const;

``````

.cpp

``````
int32 UMyObject::GetClosestRotationIndex(FRotator TargetRotation, const TArray<FRotator>& RotationsArray) const
{

int32 Index = 0;
float DeltaAngle = FQuat::Error(TargetRotation.Quaternion(), RotationsArray[Index].Quaternion());

for (int32 i = 0; i < RotationsArray.Num(); i++)
{
const  float TempDelta = FQuat::Error(TargetRotation.Quaternion(), RotationsArray*.Quaternion());

if (DeltaAngle > TempDelta)
{
DeltaAngle = TempDelta;
Index = i;
}
}

return Index;
}

``````

Awesome, thank you so much @Mhousse1247 , that looks rock solid.

I thought this code as so worthy that I’ve taken the liberty of writing a test for it.

MiscTest.cpp

``````

#include "mxbox.h"
#include "AutomationTest.h"
#include "MXBlueprintFunctionLibrary.h"

bool FMiscTest::RunTest(const FString& Parameters)
{
TArray<FRotator> RotationArray;
RotationArray.Push(FRotator(0.f , 0.f  , 0.f));
RotationArray.Push(FRotator(0.f , 0.f  , 90.f));
RotationArray.Push(FRotator(0.f , 90.f , 180.f));
RotationArray.Push(FRotator(90.f, 180.f, 270.f));

TestEqual(TEXT("Testing GetClosestRotationIndex 0"), UMXBlueprintFunctionLibrary::GetClosestRotationIndex(FRotator(0.f , 11.f , 20.f ), RotationArray), 0);
TestEqual(TEXT("Testing GetClosestRotationIndex 1"), UMXBlueprintFunctionLibrary::GetClosestRotationIndex(FRotator(0.f , 0.f  , 95.f ), RotationArray), 1);
TestEqual(TEXT("Testing GetClosestRotationIndex 2"), UMXBlueprintFunctionLibrary::GetClosestRotationIndex(FRotator(0.f , 93.f , 186.f), RotationArray), 2);
TestEqual(TEXT("Testing GetClosestRotationIndex 3"), UMXBlueprintFunctionLibrary::GetClosestRotationIndex(FRotator(80.f, 180.f, 240.f), RotationArray), 3);

return true;
}

``````

Please note, to any passers by, this is my first ever unit test - so please tread with caution (and please feel free to critique)

If anybody needs help implementing this, please shout and I’ll be happy to help.

Best,
James