OpenGL:将圆柱体旋转 90 度后变形

OpenGL: cylinder misshaped after turning it 90 degree

我和我的大学项目合作伙伴正在做这个项目。我们用 c++ 和 OpenGL 2.1 编写这个 freeglut.lib 我们将圆柱体旋转 90 度放在地面上。现在圆柱体很奇怪 misshaped. How can we fix the misshape? Is this a perspective thing? We wanted to use the cylinder later as wheels for a car which we should animate driving in a circle track. Right now the wheels on the car 只有 2D 圆。

void draw_cylinder(GLfloat radius,
    GLfloat height,
    GLubyte R,
    GLubyte G,
    GLubyte B)
{
    GLfloat x = 0.0;
    GLfloat y = 0.0;
    GLfloat angle = 0.0;
    GLfloat angle_stepsize = 0.1;

    /** Draw the tube */
    glColor3ub(R - 40, G - 40, B - 40);
    glBegin(GL_QUAD_STRIP);
    angle = 0.0;
    while (angle < 2 * PI) {
        x = radius * cos(angle);
        y = radius * sin(angle);
        glVertex3f(x, y, height);
        glVertex3f(x, y, 0.0);
        angle = angle + angle_stepsize;
    }
    glVertex3f(radius, 0.0, height);
    glVertex3f(radius, 0.0, 0.0);
    glEnd();

    /** Draw the circle on top and bottom of cylinder */
    glColor3ub(R, G, B);
    glBegin(GL_POLYGON);
    angle = 0.0;
    while (angle < 2 * PI) {
        x = radius * cos(angle);
        y = radius * sin(angle);
        glVertex3f(x, y, height);
        angle = angle + angle_stepsize;
    }
    glVertex3f(radius, 0.0, height);
    glEnd();
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    glTranslatef(0.0, -0.4, -3.0);
    //glRotatef(-40, 1.0, 0.0, 0.0);
    glRotatef(-200, 1.0, 0.0, 0.0);

    draw_cylinder(0.3, 0.5, 255, 160, 100);

    glFlush();
}

void reshape(int width, int height)
{
    if (width == 0 || height == 0) return;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(40.0, (GLdouble)width / (GLdouble)height,
        0.5, 20.0);

    glMatrixMode(GL_MODELVIEW);
    glViewport(0, 0, width, height);
}

int main(int argc, char** argv)
{
    /** Initialize glut */
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(640, 480);
    glutCreateWindow("Create Cylinder");
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);

    glutMainLoop();

    return 0;
}

您需要启用 Depth Test:

glEnable(GL_DEPTH_TEST);

并清除深度缓冲区

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

示例:

float angle = 0.0f;
void display(void)
{
    glEnable(GL_DEPTH_TEST);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glTranslatef(0.0, -0.4, -3.0);
    glRotatef(angle, 0.0, 1.0, 0.0);
    angle += 0.1f;
    glRotatef(-200, 1.0, 0.0, 0.0);

    draw_cylinder(0.3, 0.5, 255, 160, 100);

    glFlush();
    glutPostRedisplay();
}