簡體   English   中英

計算 2 點的角度

[英]Calculate Angle of 2 points

給定 P1 和 P2,我怎樣才能得到從 P1 到 P2 的角度? 謝謝

它只是float angle = atan2(p1.y - p2.y, p1.x - p2.x)

當然,返回類型是以弧度為單位的,如果您需要以度為單位,只需做angle * 180 / PI

好的記得高中的三角戀。 這就是我得到的。

兩點是 A(x1,y1) 和 B(x2,y2)

我假設您想要兩點與原點 O(0,0) 之間的角度。

好吧,每個點都構成一個以高度、底邊和斜邊為邊界的三角形,所以你會得到兩個角 alpha1 和 alpha2。 我們的想法是找到其中的每一個並計算您所需的角度β,通過執行 beta = alpha1 - alpha2 其中 alpha1 使得 alpha1 > alpha2。

計算 alpha1 = inv_tan(y1/x1) 和 alpha2 = inv_tan(y2/x2)

然后做 beta = alpha1 - alpha2

//This working code is for windows hdc mouse coords gives the angle back that is used in windows. It assumes point 1 will be your origin point
// Tested and working on VS 2017 using 2 mouse coordinates in hdc.
//
//code to call our function.
float angler = get_angle_2points(Point1X, Point1Y, Point2X, Point2Y);


// Takes 2 Window coords(points), turns them into vectors using the origin and calculates the angle around the xaxis between them.
// This function can be used for any hdc window. Ie 2 mouse points.
float get_angle_2points(int p1x, int p1y, int p2x,int p2y)
{
    //Make point1 the origin, make point2 relative to the origin so we do point1 - point1, and point2-point1,
    //since we dont 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


    // returned angle can now be used in the c++ window function used in text angle alignment. ie plf->lfEscapement = angle*10;
    return angleInDegrees;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM