2012-04-17 124 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