Calculating degrees between 2 points with inverse Y axis

我的未来我决定 提交于 2019-12-02 18:33:56

Suppose you're at (a, b) and the object is at (c, d). Then the relative position of the object to you is (x, y) = (c - a, d - b).

Then you could use the Math.atan2() function to get the angle in radians.

var theta = Math.atan2(-y, x);

note that the result is in the range [-π, π]. If you need nonnegative numbers, you have to add

if (theta < 0)
   theta += 2 * Math.PI;

and convert radians to degrees, multiply by 180 / Math.PI.

If your coordinates are (xMe, yMe) and their coordinates are (xThem, yThem), then you can use the formula:

arctan((yMe-yThem)/(xThem-xMe))

Normally it'd be arctan((yThem-yMe)/(xThem-xMe)), but in this case the sign of the y-axis is reversed.

To convert the result from radians to degrees multiply by 180/pi.

So in JavaScript, this would look like: Math.atan((yThem-yMe)/(xThem-xMe))*180/Math.PI

atan gives a value between -pi/2 and pi/2 (that is, between -90 and 90 degrees). But you can look at what quadrant your (xThem - xMe, yMe - yThem) vector is in and adjust accordingly.

In layman's terms:

function pointDirection(x1, y1, x2, y2) {
    return Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
}

In HTML5 canvas the origin is the top left corner hence the y axis grows from top to bottom. So regardless of wherever you are on the unit circle to calculate the angle of point A to the center(C) you should in fact do like

angle = Math.atan2(Cy-Ay,Ax-Cx)

and you will get your result in the range of [-π, π].

I have no idea why they haven't made the canvas origin the bottom left corner.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!