# How could I figure out the shortest way to turn, and whats the angle? [duplicate]

I'm creating some robots for my tank game. I want them to find each other and shoot each other down, so I'm trying to implement a way for them to turn towards each other, and turn the shortest way. For instance, if we where T1 (tank 1), how could I figure out if I where to turn right of left, and at what angle to turn if

• Tank1 (us) position is (8906,76), facing is 23 degrees.
• Tank2 (enemy) position is (888,61)

0/360 is straight up.

The way I've tried to do is to decide what quadrant the enemy is of myself. But that leaves out a 45 degree angle to fail. I know there is some archtan but I cant simply get a grip on them...

• – MichaelHouse Aug 19 '13 at 21:14
• If you're using Unity, check out Mathf.DeltaAngle(). – Russell Borogove Jul 14 '14 at 17:20

TLDR, if the difference between the angle you're facing, and the angle of the direction of Tank2 is between 0 and 180 degrees, then you turn left, else turn right. (might be the opposite depending on the + and - signs of whatever library you happen to be using, but you get the idea)

So you need the angle you're facing and the angle of the direction to Tank2. You already have your angle, so you get the angle to Tank2 by doing the Arc Tangent of his position in relation to you. So you get the tangent of this angle, which is the delta of the Y coordinates divided by the X coordinates.

So tan = (y2 - y1) / (x2 - x1)

Then angleToTank2 = atan(tan)

delta = angleToTank2 - yourAngle

Finally, if delta is between 0 and 180 degrees, you turn left, else, turn right.

I cannot give you exact code without knowing which libraries you're using, maybe left and right needs to be inverted. Maybe it's radians instead of degrees (180 degrees is 1 PI radians). But that should be easy for you to adjust. You might also want to add an error margin for the tank to not turn if the delta is too small (almost in the right direction, so I don't need to turn).

Hope that helps.

• Note that in most cases you should use atan2 instead of atan. It handles the divide by zero case, as well as figuring out which quadrant you're in. – amitp Aug 19 '13 at 22:35