【问题标题】:Find angle between two points找到两点之间的角度
【发布时间】:2018-02-06 17:50:56
【问题描述】:

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

但是,我没有计算角度的好方法。我得到 x 的差异和 y 的差异,并使用 Δy/Δx 的反正切。象限 1 中得到的角度是正确的,但其他三个象限是错误的。象限 2 的范围从 -1 到 -90 度。象限 3 总是等于象限 1,象限 4 总是等于象限 4。我可以用一个方程来找出两点之间的角度(从 1 到 360 度)吗?

注意:我不能使用 atan2(),而且我不知道什么是向量。

【问题讨论】:

标签: math angle mit-scratch


【解决方案1】:
// 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;
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果您无法直接使用 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
      

      【讨论】:

        【解决方案4】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-09
          相关资源
          最近更新 更多