Get bearings in JS

2012-08-21

Simple script to get the bearings (the angle) of a line relative to a starting point.

You can use this for your maps voodoo, or just like me, in a game. The script is utterly simple, as long as you understand the concepts of atan2 ;)

Code:
function getBearing(x1,y1,x2,y2) {
return Math.atan2((y2-y1), (x2-x1)); // get bearing in radians
}

As it says in the comment, the returned value is in radians (so in terms of "one circle is 2*PI"). You gotta do some 360 magic to get to degrees, but I'll leave that as an exercise for the reader ;)