使用反余弦的线之间的绝对角度

tip*_*low 4 trigonometry inverse ios

我想用反余弦函数计算由三个点(其中一个点是两条线的交点)形成的两条线之间的角度,如下所示:

CGFloat a = initialPosition.x - origin.x;
CGFloat b = initialPosition.y - origin.y;
CGFloat c = currentPosition.x - origin.x;
CGFloat d = currentPosition.y - origin.y;
CGFloat angle = (180/M_PI) * acosf(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
Run Code Online (Sandbox Code Playgroud)

不幸的是,acosf仅返回介于0和pi之间的值.如何找到介于0和2*pi之间的值(例如,以逆时针方式)?

and*_*oke 7

我不知道你正在使用什么语言,但通常有一个atan2函数可以提供360度的全部值.在这种情况下,您需要使用它两次,然后添加一些额外的逻辑.

一些伪代码将有助于清理事物:

initialAngle = atan2(initialPosition.y - origin.y, initialPosition.x - origin.x)
currentAngle = atan2(currentPosition.y - origin.y, currentPosition.x - origin.x)
# angle is measured from x axis anti-clock, so lets find the value starting from
# initial and rotating anti-clock to current, as a positive number
# so we want current to be larger than initial
if (currentAngle < initialAngle) {currentAngle += 2 pi}
# and then we can subtract
return currentAngle - initialAngle
Run Code Online (Sandbox Code Playgroud)

我知道这不是使用acos,但这是多值的,所以这样做最终会使用大量关于容易出错的差异迹象的逻辑.atan2就是你想要的.