0
\$\begingroup\$

I have unit Vector of acceleration in local space of object. Now I want to calculate Cardinal Direction from (North, East, South, West).

So Far I tried to:

FQuat QRot = LocalAcceleration.ToOrientationQuat();
    FRotator Rot = FRotator(QRot);
    float Angle = Rot.Yaw;
    float Angle2 = (FMath::RoundToInt(Angle) + 360) % 360;

(Another version was calulcating atan2).

Then:

if (FMath::IsWithin(IntAngle, 0, 46)
    && FMath::IsWithin(IntAngle, 314, 0))
{
    NewDir = EFourCardinalDirection::N;
}
if (FMath::IsWithin(IntAngle, 134, 228))
{
    NewDir = EFourCardinalDirection::S;
}
if (FMath::IsWithin(IntAngle, 46, 136))
{
    NewDir = EFourCardinalDirection::E;
}
if (FMath::IsWithin(IntAngle, 229, 313))
{
    NewDir = EFourCardinalDirection::W;
}

I also tried to calculate eighth directions and then just assign the four based on the previous eight.

Neither way provided stable results. There are some jumps between directions depending on object movement.

\$\endgroup\$
  • \$\begingroup\$ I actually need to calculate it only for 2 dimensions. The intended use is to calculate cardinal direction in which character is moving and the select animation based on the cardinal direction. \$\endgroup\$ – Łukasz Baran Feb 25 '18 at 19:12
  • 1
    \$\begingroup\$ This previous question includes some methods for solving this with 16 directions. For 4 or 8 you can simplify a bit further. \$\endgroup\$ – DMGregory Feb 25 '18 at 19:31
  • \$\begingroup\$ Feel free to post an answer then showing how you solved it. The other question isn't an exact duplicate, I don't think. \$\endgroup\$ – DMGregory Feb 25 '18 at 21:08
0
\$\begingroup\$

Here is solution:

float Atan2Angle = FMath::Atan2(LocalVelocity.Y, LocalVelocity.X);
int32 Dir = FMath::RoundToInt((Atan2Angle * 2 / PI) + 4) % 4;

LocalVelocity - Unit vector of character velocity In local space.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.