简体   繁体   English

如何在OpenGL中绘制一个立方体?

[英]How to draw a cube in OpenGL?

I need a help. 我需要帮助。 I have found several solutions to draw cube in OpenGl, but I have a problem. 我发现了几种在OpenGl中绘制立方体的解决方案,但是我有一个问题。

My code is: 我的代码是:

    wglMakeCurrent(pDC->m_hDC, m_hrc);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glTranslatef(1.5f, 0.0f, -7.0f);  // Move right and into the screen

glBegin(GL_QUADS);                // Begin drawing the color cube with 6 quads
                                  // Top face (y = 1.0f)
                                  // Define vertices in counter-clockwise (CCW) order with normal pointing out
glColor3f(0.0f, 1.0f, 0.0f);     // Green
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);

// Bottom face (y = -1.0f)
glColor3f(1.0f, 0.5f, 0.0f);     // Orange
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);

// Front face  (z = 1.0f)
glColor3f(1.0f, 0.0f, 0.0f);     // Red
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);

// Back face (z = -1.0f)
glColor3f(1.0f, 1.0f, 0.0f);     // Yellow
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, -1.0f);

// Left face (x = -1.0f)
glColor3f(0.0f, 0.0f, 1.0f);     // Blue
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);

// Right face (x = 1.0f)
glColor3f(1.0f, 0.0f, 1.0f);     // Magenta
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glEnd();  // End of drawing color-cube

glFlush();                  

SwapBuffers(pDC->m_hDC);
wglMakeCurrent(NULL, NULL);

Bellow is the image I want to get and the image I get. 贝娄是我想要的图像,也是我得到的图像。 expected image and the image I get 预期的图像和我得到的图像

How to solve this problem? 如何解决这个问题呢? Thanks in advance. 提前致谢。

You'll have to enable depth testing. 您必须启用深度测试。 Otherwise triangles are drawn in the order the are given in code which leads to overdraws even if a triangle is behind another one. 否则,将按照代码中给定的顺序绘制三角形,即使三角形在另一个三角形后面,也会导致过度绘制。 To enable depth-testing call 启用深度测试通话

glEnable(GL_DEPTH_TEST);

before issuing the first draw-call. 在发出第一个抽奖电话之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM