找出两点之间的角度

Find angle between two points

我正在尝试使图像向我的鼠标指针移动。基本上,我得到点之间的角度,并沿 x 轴移动角度的余弦值,并沿 y 轴移动角度的正弦值。

但是,我没有计算角度的好方法。我得到 x 的差异和 y 的差异,并使用 Δy/Δx 的反正切。第一象限的结果角度是正确的,但是其他三个象限是错误的。象限 2 的范围是 -1 到 -90 度。第 3 象限始终等于第 1 象限,第 4 象限始终等于第 4 象限。是否有一个方程可用于计算两点之间 1-360 度的角度?

注意:我不会用atan2(),也不知道向量是什么

如果您无法直接使用atan2(),您可以自行实现其内部计算:

atan2(y,x) =    atan(y/x)   if x>0
                atan(y/x) + π   if x<0 and y>0
                atan(y/x) - π   if x<0 and y<0

关于atan2 的答案是正确的。作为参考,这里是 Scratch 块形式的 atan2:

这是我使用的代码,它似乎工作得很好。

atan(x/y) + (180*(y<0))

其中 X 是点的 X 之间的差异 (x2 - x1),Y 是 Y 之间的差异 (y2 - y1)。

atan((x2-x1)/(y1-y2)) + (180*((y1-y2)<0))

// This working code is for Windows HDC mouse coordinates gives the angle back that is used in Windows. It assumes point 1 is your origin point
// Tested and working on Visual Studio 2017 using two mouse coordinates in HDC.
//
// Code to call our function.
float angler = get_angle_2points(Point1X, Point1Y, Point2X, Point2Y);


// Takes two window coordinates (points), turns them into vectors using the origin and calculates the angle around the x-axis between them.
// This function can be used for any HDC window. I.e., two mouse points.
float get_angle_2points(int p1x, int p1y, int p2x,int p2y)
{
    // Make point1 the origin, and make point2 relative to the origin so we do point1 - point1, and point2-point1,
    // Since we don’t need point1 for the equation to work, the equation works correctly with the origin 0,0.
    int deltaY = p2y - p1y;
    int deltaX = p2x - p1x; // Vector 2 is now relative to origin, the angle is the same, we have just transformed it to use the origin.

    float angleInDegrees = atan2(deltaY, deltaX) * 180 / 3.141;

    angleInDegrees *= -1; // Y axis is inverted in computer windows, Y goes down, so invert the angle.

    //Angle returned as:
    //                      90
    //            135                45
    //
    //       180          Origin           0
    //
    //
    //           -135                -45
    //
    //                     -90


    // The returned angle can now be used in the C++ window function used in text angle alignment. I.e., plf->lfEscapement = angle*10;
    return angleInDegrees;
}