Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the angle between the horizontal and a line through two points

Tags:

javascript

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;
}
like image 540
Jim Andrews Avatar asked Dec 27 '22 15:12

Jim Andrews


1 Answers

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
like image 194
pimvdb Avatar answered May 20 '23 22:05

pimvdb