开发者

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

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 th开发者_开发百科is, 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜