Oliver Dixon
Oliver Dixon

Reputation: 7424

NodeJS, multiple attempts at getting 360 angle between two points fails

I'm trying to simple get the angle between two points in Node JS, I've gone though a few answers and none of them seem to work.

Here's what I've got so far as a test.js file.

function getDegree(x1,y1, x2,y2) {
    var dy = y2 - y1;
    var dx = x2 - x1;
    var theta = Math.atan2(dy, dx); // range (-PI, PI]
    theta *= 180 / Math.PI; // rads to degs, range (-180, 180]

    // range [0, 360)
    if (theta < 0) {
        theta = 360 + theta;
    }

    return theta;
}

function output(expected, angle) {
    console.log('\n');
    var result = getDegree(angle[0], angle[1], angle[2], angle[3]);
    console.log('getDegree(' + angle + ') = ' + result);
    console.log('Expected: ' + expected + ', Result: ' + result + ' : ' + (expected == result));
}

var angle = [0,0, 0,0]; //(Current Pos), (Pos to Go to)

angle = [0,0,0,0];
output(0, angle);

angle = [0,0,0,9];
output(0, angle);

angle = [0,0,9,0];
output(90, angle);

angle = [0,0,0,-9];
output(180, angle);

angle = [0,0,-9,0];
output(270, angle);

// Should be 90ish
angle = [5,5,31,4];
output(90, angle);

module.exports = {
    getDegree: getDegree
};

And the output by running directly from node in the same directory.

var test = require('./test');

getDegree(0,0,0,0) = 0
Expected: 0, Result: 0 : true

getDegree(0,0,0,9) = 90
Expected: 0, Result: 90 : false

getDegree(0,0,9,0) = 0
Expected: 90, Result: 0 : false

getDegree(0,0,0,-9) = 270
Expected: 180, Result: 270 : false

getDegree(0,0,-9,0) = 180
Expected: 270, Result: 180 : false

// 90ish
getDegree(5,5,31,4) = 357.7974018382342
Expected: 90, Result: 357.7974018382342 : false

Upvotes: 0

Views: 99

Answers (1)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9880

The angle you are looking for is different from what math.atan2 gives you.i made this image , try to understand it.

enter image description here

so what you can do ? swap y and x.

you should substitute angle from 90 .

θ -> 90-θ
tan(90- θ) = cot θ    // you can use this one too without interchanging x and y 
cot  θ = 1 / tan θ    // so that's why you should swap x and y 

as you can see you have to use 1/tan θ same as swapping y and x

var theta = Math.atan2(dx, dy);

Upvotes: 1

Related Questions