Math.atan2( y, x ) is the cornerstone of any nutritious breakfast. Seriously, if you need to get from point A to point B then you’ll want this little gem in your pocket. Trouble is, if you don’t use it often – like me – you’ll forget how to use it. Which is what happened to me last night. I was drawing lines all over the place except for where I wanted them. So I stepped back and built this little explorer so that I could nail it down.

Drag the circles around and you’ll see the values change. The thin black line between the two circles is being drawn very simply by moving to the center of the blue circle and then drawing the line to the center of the green circle. The thicker red line is being drawn by moving to the center of the blue circle and then drawing a line in the direction of the green circle by calculating the distance and angle.

view source

The advantage of using the approach of the red line is that I could, if I wanted, draw the line from the edges of the circles, instead of to the midpoints. Or maybe I would want to animate the line growing from the blue to the green circle. There are all sorts of scenarios where you'll need to use the red line approach.

We think in terms of x/y coordinates but the Math.atan2 method takes it's parameters as Math.atan2( y, x ); That's y before x. Y before X. Remember, remember, remember: Math.atan2( y, x ); Do you know what happens when you forget? You get a line going exactly where you don't want it and then if you're like me you start checking your math for errors everywhere except where the error actually is.

What do you think?