# iOS开发学习OpenGL ES系列 -- 摄像机

``````attribute vec4 position;
attribute vec4 color;

varying vec4 fColor;

uniform mat4 pMatrix;
uniform mat4 vMatrix;
uniform mat4 mMatrix;

void main(void) {
fColor = color;
mat4 mvp = pMatrix * vMatrix * mMatrix;
gl_Position = mvp * position;
}
``````

mMatrix、vMatrix、pMatrix分别是模型矩阵、观察矩阵、投影矩阵。这里将mvp直接相乘，结果再与position相乘。注意相乘的顺序先进行模型矩阵变换，再是观察矩阵，最后是投影矩阵变换。

``````GLKMatrix4 projectionMatrix; // 投影矩阵
GLKMatrix4 modelMatrix; // 模型矩阵
GLKMatrix4 cameraMatrix; // 观察矩阵
``````

``````// projectionMatrix 投影矩阵。 呈现更为真实的3D效果这里设置投影矩阵为透视投影。
float aspect = self.view.frame.size.width / self.view.frame.size.height;
projectionMatrix = GLKMatrix4MakePerspective(fovyRadians, aspect, 0.0, 100.0);

// modelMatrix 模型矩阵 初始化模型矩阵为单位矩阵
modelMatrix = GLKMatrix4Identity;

// cameraMatrix 观察矩阵
cameraMatrix = GLKMatrix4MakeLookAt(0, 0, 2, 0, 0, 0, 0, 1, 0);
``````

GLKit提供了创建观察矩阵的函数：
GLKMatrix4MakeLookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ)

``````GLuint modeLocation = glGetUniformLocation(program, "mMatrix");
glUniformMatrix4fv(modeLocation, 1, 0, modelMatrix.m);

GLuint projectionLocation = glGetUniformLocation(program, "pMatrix");
glUniformMatrix4fv(projectionLocation, 1, 0, projectionMatrix.m);

GLuint cameraLocation = glGetUniformLocation(program, "vMatrix");
glUniformMatrix4fv(cameraLocation, 1, 0, cameraMatrix.m);
``````

``````// cameraMatrix = GLKMatrix4MakeLookAt(0, 0, 2, 0, 0, 0, 0, 1, 0);
cameraMatrix = GLKMatrix4MakeLookAt(0, 1, 2, 0, 0, 0, 0, 1, 0);
``````

``````// cameraMatrix = GLKMatrix4MakeLookAt(0, 1, 2, 0, 0, 0, 0, 1, 0);
cameraMatrix = GLKMatrix4MakeLookAt(0, sin(change), 3, 0, 0, 0, 0, 1, 0);
``````

``````// cameraMatrix = GLKMatrix4MakeLookAt(0, sin(change), 3, 0, 0, 0, 0, 1, 0);
cameraMatrix = GLKMatrix4MakeLookAt(0, sin(change), 3, 0, 0, 0, 1, 0, 0);
``````