Robot Trigonometry: How atan2 Finds a Target Heading

How robots find distance, get a target heading with atan2, and take the shorter turn, plus a Webots test of turning times with and without normalization.

Author
AuthorAuthor

AI Engineer · 36+ years in IT · Japanese, based in Manila for 13+ years

Robot Trigonometry: How atan2 Finds a Target Heading

Summary

  • When a robot heads toward a target, it finds the distance with the Pythagorean theorem and the direction with atan2 (a function that returns an angle from the x and y coordinates). If you find the direction with atan(y ÷ x) alone (atan returns an angle from the ratio of y to x only), the robot faces the opposite way when the target's x coordinate is negative.
  • Keep the difference between the current heading and the target heading within -180 to 180 degrees before turning, and the robot turns the short way. To go from 170 degrees to -170 degrees, a 20-degree turn is enough instead of -340 degrees.
  • In a test in the Webots robot simulator with the e-puck robot, the robot stopped at almost the same places either way, but without keeping the difference in range, the total turning time grew from 11.328 seconds to 19.072 seconds.

Consider a warehouse robot that needs to reach a shelf. It needs two pieces of information: how far away the shelf is and which direction it lies in. The robot compares that direction with its current heading to work out how far to turn.

If the heading calculation is wrong, the robot drives off in the opposite direction or wastes almost a full turn.

Use the Pythagorean Theorem to Find the Distance to a Target

We describe the target's position relative to the starting point using x and y coordinates in meters. In this article's figures and examples, x is the horizontal axis and y is the vertical axis. For coordinates measured relative to the robot itself, the convention of ROS (Robot Operating System), set out in its standard REP 103, defines x as forward, y as left, and z as up.

The straight-line distance to the target is the long, slanted side of a right triangle whose other two sides are the horizontal and vertical distances. You can find it with the Pythagorean theorem.

  • For a target 0.3 m across and 0.4 m up, the distance is the square root of (0.3² + 0.4²), which is 0.5 m
  • Python's hypot function performs exactly this Pythagorean theorem calculation

A 3:4:5 Triangle Keeps Its Angles at Any Size

A triangle with sides of 0.3 m, 0.4 m, and 0.5 m has a side ratio of 3:4:5. Triangles with the same side ratio are called similar, and their angles stay the same even when their size changes.

Enlarging a map changes the distances on the page while preserving directions. A shelf 30 m across and 40 m up therefore lies in the same direction from the starting point as a target 0.3 m across and 0.4 m up.

Sine, Cosine, and Tangent Describe the Direction

The direction of a target can be expressed with the side ratios of a right triangle. Here we use target A, which is 0.4 m across and 0.3 m up. The horizontal and vertical lengths are swapped from the distance example above, but the distance is the same 0.5 m. We look at the angle between the positive x axis and the line toward the target.

NameCalculationValue
cos (cosine)across ÷ slanted side = 0.4 ÷ 0.50.8
sin (sine)up ÷ slanted side = 0.3 ÷ 0.50.6
tan (tangent)up ÷ across = 0.3 ÷ 0.40.75

The direction here is about 36.87 degrees from the horizontal axis.

On the Unit Circle, Cosine Is x and Sine Is y

On the unit circle, which has a radius of 1, the point at angle θ has x-coordinate cos θ and y-coordinate sin θ. For a target at distance d, the position is:

  • x = d cos θ
  • y = d sin θ

If you know the distance and direction, you can use these formulas to recover the target's coordinates. The warehouse example later uses these formulas to check the calculation.

Degrees and Radians

Robot programs usually handle angles in radians (rad). The ROS convention also uses radians as the unit for angles. I explain radians and the units of angular velocity in robot units and radians.

DegreesRadians
180 degreesπ ≈ 3.1416 rad
About 57.2958 degrees1 rad
360 degrees (one full turn)2π ≈ 6.2832 rad

In Python, the math.degrees function converts radians to degrees, and the math.radians function converts degrees to radians. Use radians for calculations and convert to degrees for display to keep the units consistent.

Also note that the graphs of sin and cos repeat every 360 degrees, with values between -1 and 1.

Try it: degrees, radians and angular velocity
90° ≈ 1.5708 rad
Same angle in radians
1.5708 rad
90 × π ÷ 180

The thick blue arc has the same length as the radius when the angle is 1 rad (about 57.2958°).

Angular velocity
3.1416 rad/s
2π ÷ 2 s

One full turn is 360° = 2π rad ≈ 6.2832 rad.

atan and atan2: Finding the Angle from the Side Ratio

In the table above, the horizontal and vertical lengths of target A gave a tan value of 0.75. Now we go the other way and find the angle whose tan is 0.75. Functions that find an angle from a side ratio are called inverse trigonometric functions, and atan is one of them.

  • asin(0.5) = 30 degrees (asin finds the angle from a sin value)
  • atan(0.75) ≈ 36.87 degrees

Why atan Gives the Opposite Direction When x Is Negative

If you pass y ÷ x to atan, it returns an angle, but according to the Python documentation, the result is between -π/2 and π/2 (-90 to 90 degrees). That range covers directions within 90 degrees of the positive x axis. Targets B and C in the table below have negative x coordinates, so atan(y ÷ x) returns the opposite direction for both.

atan2(y, x), on the other hand, returns a result between -π and π (-180 to 180 degrees). For targets A and C in the table below, y ÷ x is 0.75 in both cases. If you pass only the ratio to atan, both come out as about 36.87 degrees. atan2(y, x) takes x and y separately and uses the sign of each to tell the directions of A and C apart.

The table below compares the directions from atan2 and atan(y ÷ x) for four targets, all 0.5 m away in different directions.

Targetx, y (m)atan2 directionatan(y ÷ x) direction
A0.4, 0.336.87 degrees36.87 degrees
B-0.3, 0.4126.87 degrees-53.13 degrees (opposite)
C-0.4, -0.3-143.13 degrees36.87 degrees (opposite)
D0.3, -0.4-53.13 degrees-53.13 degrees

For targets with a negative x (B and C), atan(y ÷ x) returns the opposite direction. When you calculate a robot's heading, atan2 is the standard choice.

Keep the Angle Difference Within -180 to 180 Degrees Before Turning

Subtract the robot's current heading from the target heading to find how far it should turn. The part that needs care here is how the angle difference is handled.

The yaw angle (the robot's heading on the floor) returned by the Webots InertialUnit (a sensor that measures orientation) is in the range -π to π, and so is the result of atan2. Both headings are within -180 to 180 degrees. Their difference can range from -360 to 360 degrees.

For example, say the current heading is 170 degrees and the target heading is -170 degrees.

  • Using the plain difference gives -170 − 170 = -340 degrees (the long way, almost a full turn)
  • Keeping it within -180 to 180 degrees gives 20 degrees (the short way)

Here, positive angles are counterclockwise and negative angles are clockwise. To go from 170 degrees to -170 degrees, the robot can turn 340 degrees clockwise or 20 degrees counterclockwise, and either way it ends up facing the same direction.

The angle differences here range from -360 to 360 degrees. If the difference is greater than 180 degrees, subtract 360 degrees; if it is less than -180 degrees, add 360 degrees. Keeping the difference within -180 to 180 degrees this way is called angle normalization.

With a starting heading of 160 degrees, the turning angles toward targets A to D are as follows.

TargetPlain differenceKept within -180 to 180 degrees
A36.87 − 160 = -123.13 degrees-123.13 degrees (same)
B126.87 − 160 = -33.13 degrees-33.13 degrees (same)
C-143.13 − 160 = -303.13 degrees-303.13 + 360 = 56.87 degrees
D-53.13 − 160 = -213.13 degrees-213.13 + 360 = 146.87 degrees

The calculation alone shows that C and D take a long detour in the opposite direction unless the difference is kept in range.

Try it: aim at a target with atan2
xy
  • gray: current heading
  • orange dot: target
  • blue: shorter turn
  • dashed red: plain difference
Distance to the target
0.5 m
√((-0.4)² + (-0.3)²)
Direction from atan2(y, x)
-143.13 °
-2.4981 rad
Direction from atan(y / x)
36.87 °

atan(y / x) points the opposite way (180° off) because x is negative.

Turn using the plain difference
-303.13 °
-143.13 − 160
Turn after keeping it within −180° to 180°
56.87 °

The plain difference is the long way round.

Results from Testing in Webots

I used Webots (R2025a) to check whether the e-puck moved as predicted. Before running the test, I calculated the expected result. I then compared the measurement with the prediction and treated a difference within 5% of the predicted value as a pass.

Test Conditions

  • Robot: e-puck (wheel radius 0.02 m). basicTimeStep (the length of one simulation step) is 32 ms
  • The heading during the turn was read from the yaw angle returned by the InertialUnit. The position and heading after stopping were measured with the Supervisor (a Webots feature that returns the position and rotation of objects), relative to the coordinates of the whole simulation world (I explain the Supervisor in the Webots tutorial)
  • Targets: A to D from the table above (all 0.5 m away)
  • Each time, the robot returns to the starting point (heading 160 degrees), turns toward the target heading, then drives 0.5 m
  • The turning speed was 2.0 rad/s, slowing to 0.5 rad/s once 10 degrees remained to the target heading. The stopping criterion was a difference of 1.0 degree or less from the target heading, and the driving speed was 4.0 rad/s
  • I ran two trials per target under each condition
  • The only changed condition was whether the angle difference was kept within -180 to 180 degrees

Webots world: the e-puck in the center, the x axis (red) and y axis (green), and targets A to D (yellow circles) The e-puck in the center turns toward each of the four targets shown as yellow circles and drives to it.

Turning Angle and Time

Each target row shows the turn angle and time for one trial. Each column's total covers 8 trials.

TargetAngle difference normalizedRaw angle difference
A-122.12 degrees, 1.824 secondsSame as normalized
B-32.25 degrees, 0.736 secondsSame as normalized
C56.29 degrees, 0.96 seconds-302.48 degrees, 4.032 seconds
D146.11 degrees, 2.144 seconds-212.63 degrees, 2.944 seconds
Total (8 trials)11.328 seconds19.072 seconds

Webots console: results of turning with the angle difference kept within -180 to 180 degrees With the angle difference normalized, the total turning time was 11.328 seconds.

Webots console: results of turning without keeping the angle difference in range With the raw angle difference, the robot took the long way for C and D, and the total grew to 19.072 seconds.

The robot's stopping positions were nearly the same under both test conditions. With the raw angle difference, total turning time was 7.744 seconds longer (19.072 − 11.328), or about 1.6836 times as long (19.072 ÷ 11.328).

Adding the long-way and short-way angles gives 302.48 + 56.29 = 358.77 degrees for C and 212.63 + 146.11 = 358.74 degrees for D. Both are almost a full 360-degree turn, so the numbers confirm that the long way goes around the opposite side of the short way.

Graph of target positions and stopping positions, and turning angle and time (angle difference kept in range) Left: the targets and stopping positions. Right: the turning angle and time for each target. Every turn is smaller than 180 degrees.

Graph of target positions and stopping positions, and turning angle and time (angle difference not kept in range) C and D turn more than 180 degrees. The stopping positions are almost the same as when the difference is kept in range.

Predicting the Stopping Position Error from the Heading Error

After turning, the robot's heading differed from the target heading by up to about 1 degree. Over a 0.5 m drive, that difference produces a sideways offset from the intended path. I estimated the offset in millimeters using 0.5 × sin(magnitude of the heading error) × 1000 and compared it with the Supervisor measurement.

ConditionTargetHeading error magnitudePredicted position errorMeasured position error
NormalizedA1.01 degrees8.8135 mm8.9 mm
NormalizedB0.88 degrees7.6791 mm7.8 mm
NormalizedC0.58 degrees5.0614 mm5.3 mm
NormalizedD0.76 degrees6.6321 mm6.7 mm
RawC0.65 degrees5.6722 mm5.8 mm
RawD0.5 degrees4.3633 mm4.5 mm

In every case in the table, the gap between the predicted and measured position errors was within 5% of the prediction. Under these conditions, the stopping positions were almost the same either way, so what changes is the turning time (11.328 seconds versus 19.072 seconds).

Three Robot Applications for Japanese Companies in the Philippines

These hypothetical examples show how the calculations apply in a warehouse, a restaurant, and a factory.

Warehouse: Distance and Direction for a Transport Robot

A robot goes from its charging station to pick up parts from a shelf 30 m east and 40 m north. East is 0 degrees, and the angle increases counterclockwise.

  • Distance: square root of (30² + 40²) = 50 m
  • Direction: atan2(40, 30) ≈ 53.1301 degrees
  • Check: 50 × cos 53.1301 degrees ≈ 30 m and 50 × sin 53.1301 degrees ≈ 40 m, which matches the shelf position

Calculating the position back from the distance and direction and checking that it matches the original values helps you catch mistakes in the formulas.

Restaurant: atan vs. atan2 for a Serving Robot

A robot carries food from the kitchen exit to a table 3 m west and 4 m north. West is the negative x direction, so x is -3.

  • Distance: 5 m
  • atan2(4, -3) ≈ 126.8699 degrees (northwest; the correct direction)
  • atan(4 ÷ (-3)) ≈ -53.1301 degrees (southeast; the opposite direction)

-53.1301 + 180 = 126.87, so the two are exactly 180 degrees apart. If you use atan here, the serving robot starts driving with its back to the table.

Factory: Angles That Cross the Boundary

A parts transport robot is facing 170 degrees, and the heading to its next destination is -170 degrees.

  • The plain difference is -340 degrees; kept within -180 to 180 degrees, it is 20 degrees
  • For a robot that turns 20 degrees per second, the time is 340 ÷ 20 = 17 seconds versus 20 ÷ 20 = 1 second

On a line where robots go back and forth many times a day, this difference adds up and affects the working time. Include turns that cross the 180-degree boundary in pre-deployment testing.

Frequently Asked Questions

Q: Which value comes first in atan2, x or y?

y comes first and x second. Python's atan2(y, x) uses the signs of both x and y to determine the direction and returns the angle in radians. If you reverse the order, you get a different angle with the horizontal and vertical axes swapped.

Q: Should I calculate angles in degrees or radians?

Do the calculations in radians as a rule. The ROS convention uses radians as the unit for angles, and Python's atan2 also returns its result in radians. Converting to degrees with the degrees function only for the values people check makes them easier to read.

Q: If the angle difference is not kept in range, does the robot fail to reach the target?

In this Webots test, the robot stopped at nearly the same positions under both conditions. However, the total turning time grew from 11.328 seconds to 19.072 seconds. The more a robot turns for nothing, the longer the work takes and the greater the risk of bumping into things around it.

Q: Is there a way to check that the calculations are correct before running a robot at our company?

I recommend predicting the result with a formula before you run it. Calculate the expected result, run the robot, and compare the measurement with the prediction. In my testing, I treated a difference within 5% of the predicted value as a pass. Without a prediction, you cannot tell whether a result is right or wrong.

Conclusion

The calculation for sending a robot to a target comes down to three steps.

  1. Find the distance with the Pythagorean theorem
  2. Find the direction with atan2 (with atan(y ÷ x), the robot faces the opposite way for targets with a negative x)
  3. Keep the difference from the current heading within -180 to 180 degrees before turning

In the Webots test with the e-puck, the stopping positions were almost the same whether the angle difference was kept in range or used as is. The total turning time was 19.072 seconds with the difference used as is and 11.328 seconds with it kept in range. When you deploy robots in a warehouse, restaurant, or factory, these three steps are the foundation for movement without waste.

PH AI Works is based in Manila, Philippines, and helps small and mid-sized businesses adopt AI, automate their work, and develop websites. If you are considering how to bring robots or AI into your business operations, feel free to start with a free consultation.

References

About the author

Author
Author

Founder / AI Engineer (36+ years in IT)

  • ●From Tokyo · based in Manila for 13+ years
  • ●36+ years in IT (development, SEO, AI)
  • ●Google Certified AI Professional
  • ●IBM Certified Generative AI Engineer
  • ●AI chatbots, RAG & AI agent development
  • ●Physical AI Engineer

A Japanese AI engineer with 36+ years in IT and 13+ years on the ground in the Philippines. I write from hands-on experience to help Japanese companies adopt AI that actually delivers results — chatbots, workflow automation, AI agents, and AI-driven marketing. Feel free to reach out in Japanese or English.

Your Competitors Are Already Using AI!

Is your business keeping up?