1
\$\begingroup\$

I want a function that gives me the turn direction for my object (1 or -1)

I have two angles

1 - current rotation(A)

0 <= A <= 360

2 - target rotation(B)

0 <= B <= 360

int turnSide = FindTurnSide(A, B);
Myobject.rotation += turnSpeed * turnSide;

public int FindTurnSide(int A, int B){
    //Find the closest side direction for return
    //return 1 for right side
    //return -1 for left side
}

The function should find the closest side for turn. And it should return 1 (turn right) or -1 (turn left).

How can I implement the FindTurnSide function?

\$\endgroup\$
2
\$\begingroup\$

EDIT: The answer is now correct, you had to add 360 in case of diff negative

You just have to look at the difference between the two angles. It it is between 0 and 180, you turn left (anticlockwise), otherwise right.

int FindTurnSide(int current, int target)
{
     int diff = target - current;
     if(diff < 0)
         diff += 360;
     if(diff > 180)
          return -1; // left turn
     else
          return 1; // right turn
}
\$\endgroup\$
  • 4
    \$\begingroup\$ one line code for fun ;) -> return ((target-current+360)%360 - 180>0) ? -1 : 1 \$\endgroup\$ – Blau Jul 24 '12 at 13:56
0
\$\begingroup\$

Here you go.

public static class MathF
{
    public const float TwoPi = Math.Pi * 2.0f;
    public const float RadAngle180 = Math.Pi;
    public const float RadAngle360 = TwoPi;

    public static float NormalizeAngle(float var)
    {
        if (var >= 0.0f && var < RadAngle360) return var;

        if (var < 0.0f)
            var = RadAngle360 + (var % RadAngle360);
        else
            var = var % RadAngle360;

        return var;
    }

    public static float TurnDir(float val1, float val2)
    {
        val1 = MathF.NormalizeAngle(val1);
        val2 = MathF.NormalizeAngle(val2);
        if (val1 == val2) return 0.0f;

        if (Math.Abs(val1 - val2) > RadAngle180)
        {
            if (val1 > val2) return 1.0f;
            else return -1.0f;
        }
        else
        {
            if (val1 > val2) return -1.0f;
            else return 1.0f;
        }
    }

    public static float CircularDist(float v1, float v2)
    {
        float vTemp = System.Math.Abs(NormalizeAngle(v1) - NormalizeAngle(v2));
        if (vTemp * 2.0f <= RadAngle360)
            return vTemp;
        else
            return RadAngle360 - vTemp;
    }
}
\$\endgroup\$
  • \$\begingroup\$ I think it is not useful for performance :/ \$\endgroup\$ – MarsPeople Jul 24 '12 at 19:23

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.