Heading from Point A to Point B in 2D space?

痞子三分冷 提交于 2019-12-07 19:36:15

问题


I'm working on a project which requires me to calculate the heading from a variable point A to a variable point B in 0 - 360 degrees to let the object at point A face point B.

Now, I'm unsure on how to achieve this, I googled but didn't find any good solution.

How would I calculate the heading from point A to point B in 2D space in any situation?


回答1:


In a language such as C or C++ you might use the atan2 function, which calculates the arctangent of y/x over four quadrants, taking the signs of x and y into account.

If A is at (x1, y1) and B is at (x2, y2), then the heading in radians is given by:

theta_radians = atan2(y2 - y1, x2 - x1);

The range of theta_radians is -π to +π. You can convert this to degrees in the range 0 to 360 as follows:

theta_degrees = (theta_radians + M_PI) * 360.0 / (2.0 * M_PI);

$ man atan2




回答2:


It's trig. You know the position of the two points and you can use them to make a right triangle. From that you can use SOH-CAH-TOA to find the angle you're interested in. Then from there you need to determine which quadrant the triangle is in and offset the computed angle appropriately.



来源:https://stackoverflow.com/questions/4403515/heading-from-point-a-to-point-b-in-2d-space

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