# 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?

-
– bummzack Jul 24 '12 at 8:40
You might find my answer on stackoverflow helpful: How to gradually rotate an object to face another turning the shortest distance – George Duckett Jul 24 '12 at 12:10

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
}
``````
-
Thanks for your answer but the function is not run correctly, for example FindTurnSide(0, 315) must return 2 but the function return 1. – MarsPeople Jul 24 '12 at 8:38
@Kumul Sorry, I forgot that case. You have to add 360 in case of negative `diff`. I believe the answer it is now correct. – Dan Jul 24 '12 at 9:42
And last fixing... if(diff > 180) it is running correctly now thanks (: – MarsPeople Jul 24 '12 at 10:22
one line code for fun ;) -> return ((target-current+360)%360 - 180>0) ? -1 : 1 – Blau Jul 24 '12 at 13:56
@Kumul As I can see, you are new to this site. It is important that once you like an answer you accept it. This way future user wandering the same question will now straight away the right answer. – Dan Jul 24 '12 at 16:33

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