A JavaScript question.
Below is a routine that seems to have some problems. What is the problem? The function, given two points, is supposed to return the angle (in radians) formed between the horizontal axis and the line containing the two points (X1,Y1) and (X2,Y2).
function GetAngle(X1, Y1, X2, Y2) {
if (Y2 == Y1) {
return (X1 > X2) ? Math.PI : 0;
}
if (X2 == X1) {
return (Y2 > Y1) ? Math.PI/2 : 1.5*Math.PI;
}
var tangent = (X2 - X1) / (Y2 - Y1);
var ang = Math.atan(tangent);
if (Y2-Y1 < 0) ang -= Math.PI;
return ang;
}
Why don't you use Math.atan2
, which is more convenient. It automatically does it right when both numbers are negative (which information is lost with dividing), and returns the correct values for edge cases as well.
var angle = Math.atan2(Y2 - Y1, X2 - X1);
// these return differently, even though 0 / -1 === 0 / 1
Math.atan2( 0, -1); // Math.PI
Math.atan2( 0, 1); // 0
// same thing: 1 / 1 === -1 / -1
Math.atan2( 1, 1); // Math.PI / 4
Math.atan2(-1, -1); // -Math.PI * 3 / 4
// other values
Math.atan2( 1, 1); // Math.PI / 4
Math.atan2( 1, 0); // Math.PI / 2
Math.atan2(-1, 0); // -Math.PI / 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With