旋转 2D 正方形

Rotating 2D square

本文关键字:正方形 2D 旋转      更新时间:2023-10-16

我可以旋转3D对象,但它似乎不适用于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();
}

我的代码在某种程度上有效:它确实旋转对象,但不在所需点的中心。

附言。如果需要,我可以上传完整的应用程序(Visual Studio 2010 Project,使用 FreeGLUT 和 SDL)。

我假设你实际上并没有以固定的角度旋转: 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();

默认情况下,我们经常使用几何图形以原点为中心的对象进行建模。 这样,我们可以简单地旋转对象,然后将其参考点转换为我们想要的位置。