How can I determine the direction of turn?

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?

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
}
• one line code for fun ;) -> return ((target-current+360)%360 - 180>0) ? -1 : 1
– Blau
Jul 24 '12 at 13:56

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)
else

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