Topics About Contact Resources Quotes

Interactive Find the Angle Between Two Points

Why Does Atan Give Us the Angle Between Two Points

The tan function takes in an angle and gives us the rise over run, the atan function is the inverse of the tan function, it takes in the rise over run and gives us the angle.

  • tan(angle) => rise/run
  • atan(rise/run) => angle

All we have to do is find our rise(vertical distance) and run(horizontal distance) between our points.
To find the distances we subtract our points.

Let's see it in action.

function findAngleBetween(x1, y1, x2, y2) { let calc_angle = Math.atan2(y2 - y1, x2 - x1); // notice y is the first parameter not x // y is the rise and x is the run // we could do (y2-y1, x2-x1) or (y1-y2, x1-x2) if(calc_angle < 0) // we don't want negative angles { calc_angle += Math.PI * 2; // make negative angles positive by adding 360 degrees } console.log("angle found", calc_angle * (180 / Math.PI)); // convert angle from radians to degrees then log } // notice sin is y and cos is x

We notice that with this same information we could find the distance between the points.

Let's Put it to the Test

Let's try going from an angle to rise/run back to the angle.
Given an angle we can find its rise with sine and its run with cosine. We can then plug the rise and run into our atan2 function and see if we get our original angle out.

We can learn more about these basics with the unit circle.

function proveAtan2FindsCorrectAngle(angle) { const sin = Math.sin(angle), cos = Math.cos(angle); let calc_angle = Math.atan2(sin, cos); if(calc_angle < 0) // we don't want negative angles { calc_angle += Math.PI * 2; // make negative angles positive by adding 360 degrees } console.log(angle, calc_angle, angle == calc_angle); // calc_angle will equal angle } // notice sin is y and cos is x

We always take note whether we are using degrees or radians.

Why Is It Called Atan2

We call it atan2 because it takes two arguments, it takes the y distance and the x distance. The regular atan function only takes one argument, which is the y distance divided by the x distance.

  • atan(rise/run) => angle
  • atan2(rise, run) => angle

Why Use Atan2 Instead of Atan

Atan2 has two big advantages over atan, both are due to it taking two argument which allows the atan2 function to have more information.

The first advantage is that inputting both the y and x allows atan2 to check if y or x are positive or negative, this is lost if we had done the division on our own (as we do with atan).

The second advantage is that because atan takes in the rise over run (y/x), we have a problem if x is 0.
We can never divide by zero.
We could write the code to protect against this error easily enough, but Atan2 has already done it for us.

Resources