如何获取点相对于中心点的角度?

8 投票
4 回答
7808 浏览
提问于 2025-04-18 01:31

如果我有两个点,一个是圆心 (x0,y0),另一个是圆边上的点 (x,y)(在图片中是红点)。我该如何计算这个红点的角度呢?

需要注意的是,计算出来的角度应该在0到360度之间。图片中红点的角度大约是70度。

我该如何在Python中实现这个呢?

谢谢!

这个方法似乎不太管用。

        (dx, dy) = (x0-x, y-y0)
        angle = atan(float(dy)/float(dx))
        if angle < 0:
            angle += 180

enter image description here

4 个回答

1

这段代码的作用是...

首先,它会...

接着,它会检查...

如果满足某个条件,它就会...

最后,代码会返回...

总的来说,这段代码的目的是...

希望这个解释能帮助你更好地理解这段代码!

float AnglePointToPoint(const CCPoint & pFrom, const CCPoint & pTo)
{
    float distanceX     = pTo.x - pFrom.x;
    float distanceY     = pTo.y - pFrom.y;
    float beta          = acos( fabs(distanceX) / sqrt( pow(distanceX,2) + pow(distanceY,2) ) ) * 180 / M_PI;
    float angleResult   = 0.0f;

    if( distanceX > 0 )
    {
        if( distanceY < 0 )
        {
            angleResult = beta + 90;//right_bot
        }
        else
        {
            angleResult = fabs(beta - 90);//right_top
        }
    }
    else
    {
        if( distanceY < 0 )
        {
            angleResult = fabs(beta - 90) + 180;//left_bot
        }
        else
        {
            angleResult = beta + 270;//left_top
        }
    }
    return angleResult;
}
1

哦,这个错误很常见。atan 函数返回的是弧度,而不是度数。所以你需要把角度乘以 180/pi,才能把它转换回度数。此外,你还需要把你的 dy 改成 y0 - y,这样才能和你的 dx 保持一致。下面是一些修正过的代码。

dx, dy = x0-x, y0-y
angle_in_radians = atan2(dy,dx) # you don't need to cast to float
angle_in_degrees = angle_in_radians * 180 / pi
4

除了将角度从弧度转换过来,建议使用 atan2 而不是 atan。因为 atan 对于圆的两侧的点会给出相同的答案,而 atan2 能够根据 dxdy 的正负来给出正确的角度。它需要两个参数:

angle = math.degrees(math.atan2(y0 - y, x0 - x)) % 360

需要注意的是,atan2 返回的值会在 -pipi 之间,或者说是 -180 度到 180 度之间,所以 % 360 是用来把结果调整到你想要的范围。

8

你离正确答案已经很近了 :-)

把这个:

 angle = atan(float(dy)/float(dx))

改成这个:

 angle = degrees(atan2(float(dy), float(dx)))

atan2() 函数比 atan() 更好,因为它会考虑输入的符号,并且可以绕着整个圆圈计算:

atan2(...)
    atan2(y, x)

    Return the arc tangent (measured in radians) of y/x.
    Unlike atan(y/x), the signs of both x and y are considered

degrees() 函数是用来把弧度转换成度数的:

degrees(...)
    degrees(x)

    Convert angle x from radians to degrees.

另外,正如 Rich 和 Cody 提到的,你需要修正一下你的 dy 计算。

撰写回答