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...


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.

| improve this answer | |
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – amitp Aug 19 '13 at 22:35

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