atan2 and Aiming
Sine and cosine turn an angle into a direction. atan2 does the opposite: it turns a direction into an angle. Whenever a turret, a 2D character's sprite or a top-down gun needs to "face the mouse", there is an atan2 call behind it.
Why atan2 and not atan
The plain arctangent atan(y / x) loses information: (1, 1) and (-1, -1) give the same ratio, so it cannot tell "up-right" from "down-left", and it divides by zero when x = 0. atan2(y, x) takes both components separately (note the order: y first) and returns the full angle in (-π, π].
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
int main() {
std::cout << std::fixed << std::setprecision(1);
const double toDeg = 180 / std::numbers::pi;
struct { double x, y; } dirs[] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
for (auto d : dirs) {
std::cout << "(" << std::setw(4) << d.x << ", " << std::setw(4) << d.y << ") atan2 = "
<< std::setw(6) << std::atan2(d.y, d.x) * toDeg
<< " atan(y/x) = " << std::setw(6) << std::atan(d.y / d.x) * toDeg + 0.0 << "\n";
}
}( 1.0, 0.0) atan2 = 0.0 atan(y/x) = 0.0
( 1.0, 1.0) atan2 = 45.0 atan(y/x) = 45.0
( 0.0, 1.0) atan2 = 90.0 atan(y/x) = 90.0
(-1.0, 1.0) atan2 = 135.0 atan(y/x) = -45.0
(-1.0, 0.0) atan2 = 180.0 atan(y/x) = 0.0
(-1.0, -1.0) atan2 = -135.0 atan(y/x) = 45.0
( 0.0, -1.0) atan2 = -90.0 atan(y/x) = -90.0
( 1.0, -1.0) atan2 = -45.0 atan(y/x) = -45.0
atan gets the three directions on the left half wrong, and for (0, ±1) it only works because 1/0.0 happens to be infinity in IEEE floating point. (The + 0.0 turns a negative zero into a plain 0.0 for printing.)
Aiming a turret
To aim from a turret at a target, take the arrow target - turret and feed its components to atan2. To fire, turn the angle back into a direction with cos/sin, or simply normalize the arrow (they are the same thing).
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
struct Vec2 { double x, y; };
int main() {
std::cout << std::fixed << std::setprecision(2);
const double toDeg = 180 / std::numbers::pi;
Vec2 turret{2, 2};
Vec2 targets[] = {{6, 2}, {2, 7}, {-1, -1}, {5, 6}};
for (Vec2 t : targets) {
double dx = t.x - turret.x, dy = t.y - turret.y;
double angle = std::atan2(dy, dx);
double fx = std::cos(angle), fy = std::sin(angle);
std::cout << "target (" << t.x << ", " << t.y << "): angle " << std::setw(7) << angle * toDeg
<< " deg, fire along (" << fx << ", " << fy << ")\n";
}
}target (6.00, 2.00): angle 0.00 deg, fire along (1.00, 0.00)
target (2.00, 7.00): angle 90.00 deg, fire along (0.00, 1.00)
target (-1.00, -1.00): angle -135.00 deg, fire along (-0.71, -0.71)
target (5.00, 6.00): angle 53.13 deg, fire along (0.60, 0.80)
Turning at a limited speed
Snapping straight to the target angle looks robotic. Real turrets turn at a maximum rate (degrees per second). Compute the shortest signed difference between the current and the desired angle, then clamp the step to maxTurn * dt.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <numbers>
const double PI = std::numbers::pi;
double wrapPi(double a) {
a = std::fmod(a + PI, 2 * PI);
if (a < 0) a += 2 * PI;
return a - PI;
}
double rotateTowards(double current, double target, double maxStep) {
double diff = wrapPi(target - current);
return current + std::clamp(diff, -maxStep, maxStep);
}
int main() {
std::cout << std::fixed << std::setprecision(1);
const double toRad = PI / 180, toDeg = 180 / PI;
double angle = 170 * toRad; // facing left, slightly up
double target = std::atan2(-1.0, -4.0); // target is left, slightly down (about -166 deg)
const double maxTurn = 90 * toRad; // 90 deg per second
const double dt = 0.05;
for (int frame = 1; frame <= 6; frame++) {
angle = wrapPi(rotateTowards(angle, target, maxTurn * dt));
std::cout << "frame " << frame << ": " << angle * toDeg << " deg\n";
}
std::cout << "target: " << target * toDeg << " deg\n";
}frame 1: 174.5 deg
frame 2: 179.0 deg
frame 3: -176.5 deg
frame 4: -172.0 deg
frame 5: -167.5 deg
frame 6: -166.0 deg
target: -166.0 deg
The turret crosses ±180° and arrives in a few frames, instead of spinning almost a full circle the long way round. Unity has Mathf.MoveTowardsAngle and Unreal FMath::FindDeltaAngleDegrees for exactly this.
Leading a moving target
Bullets take time to fly. To hit a target moving at constant velocity, aim where it will be. A simple, good-enough approach iterates: estimate the flight time from the current distance, predict the target's position after that time, and repeat a couple of times.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>
struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double length(Vec2 v) { return std::hypot(v.x, v.y); }
int main() {
std::cout << std::fixed << std::setprecision(3);
Vec2 gun{0, 0}, target{20, 0}, targetVel{0, 5};
const double bulletSpeed = 25;
Vec2 aim = target;
for (int i = 1; i <= 4; i++) {
double t = length(aim - gun) / bulletSpeed;
aim = target + targetVel * t;
std::cout << "iteration " << i << ": t=" << t << " aim=(" << aim.x << ", " << aim.y << ")\n";
}
double angle = std::atan2(aim.y - gun.y, aim.x - gun.x) * 180 / std::numbers::pi;
std::cout << "fire at " << angle << " deg\n";
}iteration 1: t=0.800 aim=(20.000, 4.000)
iteration 2: t=0.816 aim=(20.000, 4.079)
iteration 3: t=0.816 aim=(20.000, 4.082)
iteration 4: t=0.816 aim=(20.000, 4.082)
fire at 11.537 deg
The estimate converges quickly. The game-ai course solves the same problem exactly with a quadratic equation.
Tip: On a canvas or in screen coordinates,
ygrows downward, soatan2(dy, dx)gives angles that increase clockwise. That is fine as long as you use the same convention to rotate the sprite: canvasctx.rotate(angle)also turns clockwise for positive angles.
Test yourself
Which argument order does std::atan2 take?
- atan2(x, y)
- atan2(y, x)
- atan2(angle)
- atan2(x / y)
Why is atan(y / x) not enough for aiming?
- It is slower
- It returns degrees
- It cannot distinguish opposite directions like (1, 1) and (-1, -1)
- It only works in 3D
A turret at 170° must turn to -166°. Which way is shortest?
- Counter-clockwise by 24°
- Clockwise by 336°
- It must turn 0°
- Counter-clockwise by 336°