2010-07-02 16 views
14

以下兩種方法中的哪一種使用正確的數學來旋轉點?如果是這樣,哪一個是正確的?適當的三角法旋轉原點的位置

POINT rotate_point(float cx,float cy,float angle,POINT p) 
{ 
    float s = sin(angle); 
    float c = cos(angle); 

    // translate point back to origin: 
    p.x -= cx; 
    p.y -= cy; 

    // Which One Is Correct: 
    // This? 
    float xnew = p.x * c - p.y * s; 
    float ynew = p.x * s + p.y * c; 
    // Or This? 
    float xnew = p.x * c + p.y * s; 
    float ynew = -p.x * s + p.y * c; 

    // translate point back: 
    p.x = xnew + cx; 
    p.y = ynew + cy; 
} 
+10

我不很明白。什麼是cx和cy?另外,你已經聲明瞭你的POINT類型的函數,但是它不返回一個POINT,或者其他任何東西。 – 2010-07-02 01:09:06

+1

@Brian Hooper:+1用於指出有意義的變量名稱的好處;) – Cogwheel 2010-07-02 04:43:02

回答

22

這取決於你如何定義angle。如果是逆時針測量(這是數學約定),那麼正確的旋轉是你的第一個:

// This? 
float xnew = p.x * c - p.y * s; 
float ynew = p.x * s + p.y * c; 

但如果是順時針測量,然後第二個是正確的:

// Or This? 
float xnew = p.x * c + p.y * s; 
float ynew = -p.x * s + p.y * c; 
27

From Wikipedia

要使用的矩陣的點(x,y)與被旋轉被寫爲一個向量,然後通過從角度計算,θ,像這樣的矩陣相乘進行旋轉:

https://upload.wikimedia.org/math/0/e/d/0ed0d28652a45d730d096a56e2d0d0a3.png

其中(x',y')的是旋轉後的點的座標,並且x的公式'和y'可以被看作是

alt text

+0

不要忘記,如果你在一個典型的屏幕座標空間中工作,那麼你的y軸將從數學標準中倒過來+ y,up是-y),你需要考慮這一點。 – 2017-11-08 20:13:28

1

這是從我自己的矢量庫中提取..

//---------------------------------------------------------------------------------- 
// Returns clockwise-rotated vector, using given angle and centered at vector 
//---------------------------------------------------------------------------------- 
CVector2D CVector2D::RotateVector(float fThetaRadian, const CVector2D& vector) const 
{ 
    // Basically still similar operation with rotation on origin 
    // except we treat given rotation center (vector) as our origin now 
    float fNewX = this->X - vector.X; 
    float fNewY = this->Y - vector.Y; 

    CVector2D vectorRes( cosf(fThetaRadian)* fNewX - sinf(fThetaRadian)* fNewY, 
          sinf(fThetaRadian)* fNewX + cosf(fThetaRadian)* fNewY); 
    vectorRes += vector; 
    return vectorRes; 
} 
+2

您可以將'cosf'和'sinf'結果保存到變量中,以使用三分之一的trig函數調用。 :) – 2010-07-02 01:28:13

+0

好抓..... – YeenFei 2010-07-02 01:31:53