2012-04-17 133 views
-2

我可以旋轉3D對象,但它似乎不適用於2D。旋轉2D平方

我想旋轉我的可移動(通過箭頭)正方形向右90度(旋轉中心:正方形的中心)。我想出了一個下面的代碼:

class CSquare : public CObject { 
    SPoint pnta;   //left top corner of a square 
    uint16 len;   //length 
    bool bFill, bRotate; //filled? rotating? 
    GLubyte color[4]; //filling color 
    float angle;   //rotate for this 

public: 
    CSquare(); 
    CSquare(const CSquare &sqr); 
    CSquare(SPoint &a, uint16 l, bool fill = false); 
    CSquare(uint16 x, uint16 y, uint16 l, bool fill = false); 

    void draw(); 
    void toggleRotate(); 
    void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a); 
    void setPoint(uint16 x, uint16 y); 

    SPoint getPoint(); 
    uint16 getPosX(); 
    uint16 getPosY(); 
    uint16 getLength(); 
}; 

void CSquare::draw() { 
    glPushMatrix(); 
    if (bRotate) 
    if (++angle < 360.0f) 
    { 
     glTranslatef(pnta.nX + len/2, pnta.nY + len/2, 0); 
     glRotatef(90, 0, 0, 1); 
    } 
    else angle = 0.0f; 

    if (bFill == true) glBegin(GL_QUADS); 
    else glBegin(GL_LINE_LOOP); 
    glColor4ubv(color); 
    glVertex2i(pnta.nX, pnta.nY); 
    glColor4ub(255, 255, 0, 0); //temporary to visualise rotation effect 
    glVertex2i(pnta.nX + len, pnta.nY); 
    glColor4ub(0, 255, 0, 0); 
    glVertex2i(pnta.nX + len, pnta.nY + len); 
    glColor4ub(0, 0, 255, 0); 
    glVertex2i(pnta.nX, pnta.nY + len); 
    glEnd(); 
    glPopMatrix(); 
} 

我的代碼工作在一定程度上:它旋轉的對象,但不與期望的點爲中心。

PS。如果需要,我可以上傳完整的應用程序(Visual Studio 2010 Project,使用FreeGLUT和SDL)。

回答

1

我打算假設你實際上沒有以固定角度旋轉:glRotatef(90, 0, 0, 1);如果這不是一個抄寫錯誤,那麼應該先修復它。

也就是說,旋轉總是發生在原點周圍。你在(pnta.nX, pnta.nY)處畫出你的形狀。看起來你想圍繞形狀的中心旋轉。要做到這一點,你必須首先將該點移到原點。然後進行旋轉,然後將點回來,你想讓它:

glPushMatrix(); 
glTranslatef(pnta.nX + len/2, pnta.nY + len/2, 0); 
glRotatef(angle, 0, 0, 1); 
glTranslatef(-pnta.nX - len/2, -pnta.nY - len/2, 0); 
drawShape(); 
glPopMatrix(); 

我們經常模型其幾何形狀在默認情況下圍繞原點爲中心的對象。這樣,我們可以簡單地旋轉對象,然後將其參考點轉換爲我們想要的位置。

+0

謝謝:) 旋轉後,我沒有回來glTranslate。順便說一句,旋轉一個固定的角​​度是一個故意的行動 - 我想找出什麼是錯的,並調試它。 – Robin92 2012-04-17 19:19:14