# 学习OpenGL ES之绘制一个正方体

### 获取示例代码

- (void)drawZPlanes {
static GLfloat triangleData[] = {
-0.5,   0.5f,  0.5,   0,  0,  1,
-0.5f,  -0.5f,  0.5,  0,  0,  1,
0.5f,   -0.5f,  0.5,  0,  0,  1,
0.5,    -0.5f, 0.5,   0,  0,  1,
0.5f,  0.5f,  0.5,    0,  0,  1,
-0.5f,   0.5f,  0.5,  0,  0,  1,
-0.5,   0.5f,  -0.5,   0,  0,  1,
-0.5f,  -0.5f,  -0.5,  0,  0,  1,
0.5f,   -0.5f,  -0.5,  0,  0,  1,
0.5,    -0.5f, -0.5,   0,  0,  1,
0.5f,  0.5f,  -0.5,    0,  0,  1,
-0.5f,   0.5f,  -0.5,  0,  0,  1,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 12);
}

- (void)drawXPlanes {
static GLfloat triangleData[] = {
// X轴0.5处的平面
0.5,  -0.5,    0.5f, 1,  0,  0,
0.5,  -0.5f,  -0.5f, 1,  0,  0,
0.5,  0.5f,   -0.5f, 1,  0,  0,
0.5,  0.5,    -0.5f, 1,  0,  0,
0.5,  0.5f,    0.5f, 1,  0,  0,
0.5,  -0.5f,   0.5f, 1,  0,  0,
// X轴-0.5处的平面
-0.5,  -0.5,    0.5f, 1,  0,  0,
-0.5,  -0.5f,  -0.5f, 1,  0,  0,
-0.5,  0.5f,   -0.5f, 1,  0,  0,
-0.5,  0.5,    -0.5f, 1,  0,  0,
-0.5,  0.5f,    0.5f, 1,  0,  0,
-0.5,  -0.5f,   0.5f, 1,  0,  0,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 12);
}

- (void)drawYPlanes {
static GLfloat triangleData[] = {
-0.5,  0.5,  0.5f, 0,  1,  0,
-0.5f, 0.5, -0.5f, 0,  1,  0,
0.5f, 0.5,  -0.5f, 0,  1,  0,
0.5,  0.5,  -0.5f, 0,  1,  0,
0.5f, 0.5,   0.5f, 0,  1,  0,
-0.5f, 0.5,  0.5f, 0,  1,  0,
-0.5, -0.5,   0.5f, 0,  1,  0,
-0.5f, -0.5, -0.5f, 0,  1,  0,
0.5f, -0.5,  -0.5f, 0,  1,  0,
0.5,  -0.5,  -0.5f, 0,  1,  0,
0.5f, -0.5,   0.5f, 0,  1,  0,
-0.5f, -0.5,  0.5f, 0,  1,  0,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 12);
}

- (void)update {
[super update];
float varyingFactor = (sin(self.elapsedTime) + 1) / 2.0; // 0 ~ 1
self.cameraMatrix = GLKMatrix4MakeLookAt(0, 0, 2 * (varyingFactor + 1), 0, 0, 0, 0, 1, 0);

GLKMatrix4 rotateMatrix = GLKMatrix4MakeRotation(varyingFactor * M_PI * 2, 1, 1, 1);
self.modelMatrix = rotateMatrix;
}

- (void)drawCube {
[self drawXPlanes];
[self drawYPlanes];
[self drawZPlanes];
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
[super glkView:view drawInRect:rect];

glUniformMatrix4fv(projectionMatrixUniformLocation, 1, 0, self.projectionMatrix.m);
glUniformMatrix4fv(cameraMatrixUniformLocation, 1, 0, self.cameraMatrix.m);

glUniformMatrix4fv(modelMatrixUniformLocation, 1, 0, self.modelMatrix.m);
[self drawCube];
}

OpenGL ES