画立方体和画2D平面没有本质的区别,因为顶点坐标里面本身就包含了Z轴坐标。唯一不同的是,需要打开OpenGL的深度测试
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
通常在OpenGL里显示3D模型,会经过3个矩阵的转换
- Model 模型矩阵用了确定物体的位置。一般的纹理坐标都是已原点为中心、坐标范围(-1, 1),称之为局部空间而生成的,Model矩阵就是用来定位物体实际的位置(世界空间)
- View 观察者的位置。不同地方观察物体,看到的效果也是不同的(观察空间)
- Projection 投影矩阵可以产生近大远小大效果,并且定义了视野大范围(裁减空间)
举个例子,下面代码就定义了3个矩阵
// Create transformations
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
model = glm::rotate(model, (GLfloat)glfwGetTime() * 50.0f, glm::vec3(0.5f, 1.0f, 0.0f));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
// Get their uniform location
GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
// Pass them to the shaders
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
// Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once.
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
model定义了一个旋转角、view是在Z轴正3的位置(View和实际坐标系相反)、projection是一个45度的透视投影。
把这3个矩阵传给Shader就可以了。