</pre><strong><span style="font-size:18px">在绘制天空盒时,我们需要先构造一个立方体。这个立方体的每个顶点构成的三角形一定要符合右手定律,也就是说每个三角形的法向量要一致,否则的话如果开启cull_face话有的面能看到有的面则看不到。然后我们先构造6个纹理对象,依次为纹理对象设置图像数据,在绘制时分步绘制并分别绑定不同的纹理完成贴图,下面上一些关键代码,完整代码请参考<a target=_blank target="_blank" href="https://github.com/xuyaxiang/SkyCube.git">点击打开链接</a></span></strong><p></p><p><strong></strong></p><pre name="code" class="objc"> glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL);
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(SceneVertex), NULL+offsetof(SceneVertex, texCoord));
glEnable(GL_DEPTH_TEST);
请注意,由于我们把视点放在了立方体内部,我们一定不能开启gl_cull_face这个选项,否则我们将看不到图形,因为这个选项是要把三角形内部剔除。
glBindTexture(GL_TEXTURE_2D, tex[1]);
UIImage *image1=[UIImage imageNamed:@"pos_z.tga"];
size_t width1;
size_t height1;
NSData *data1= AGLKDataWithResizedCGImageBytes(image1.CGImage, &width1, &height1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLuint)width1, (GLuint)height1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data1.bytes);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
图像数据必需要经过一些处理以符合我们为gpu设置的数据格式
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(_program);
static float j=0;
GLfloat aspect=(GLfloat)view.drawableWidth/(GLfloat)view.drawableHeight;
GLint location=glGetUniformLocation(_program, "modelViewMatrix");
GLKMatrix4 mat=GLKMatrix4MakeLookAt(0, 0, -0.5, 0, 0, 0, 0, 1, 0);
mat=GLKMatrix4Scale(mat, 50, 50*aspect, 50);
mat=GLKMatrix4Rotate(mat, GLKMathDegreesToRadians(j++), 0, 1, 0);
glUniformMatrix4fv(location, 1, 0, mat.m);
GLint location1=glGetUniformLocation(_program, "projectionViewMatrix");
GLKMatrix4 mat1=GLKMatrix4Identity;
mat1=GLKMatrix4MakeFrustum(-1, 1, -1, 1, 0.5, 100);
glUniformMatrix4fv(location1, 1, 0, mat1.m);
glBindTexture(GL_TEXTURE_2D, tex[0]);
glDrawArrays(GL_TRIANGLES, 0, 6);//neg-z
glBindTexture(GL_TEXTURE_2D, tex[1]);
glDrawArrays(GL_TRIANGLES, 6, 6);//pos-z
分别绘制立方体的每一部分