渲染正方形并用键盘控制
绘制正方形
//blockSize 边长
GLfloat blockSize = 0.1f;
//正方形的4个点坐标
GLfloat vVerts[] = {
-blockSize,-blockSize,0.0f,
blockSize,-blockSize,0.0f,
blockSize,blockSize,0.0f,
-blockSize,blockSize,0.0f
};
void setupRC()
{
//设置清屏颜色(背景颜色)
glClearColor(0.98f, 0.40f, 0.7f, 1);
//没有着色器,在OpenGL 核心框架中是无法进行任何渲染的。初始化一个渲染管理器。
//在前面的课程,我们会采用固管线渲染,后面会学着用OpenGL着色语言来写着色器
shaderManager.InitializeStockShaders();
//图元连接方式修改为GL_TRIANGLE_FAN ,4个顶点
triangleBatch.Begin(GL_TRIANGLE_FAN, 4);
triangleBatch.CopyVertexData3f(vVerts);
triangleBatch.End();
}
特殊键位
GLfloat xPos = 0.0f;
GLfloat yPos = 0.0f;
void SpecialKeys(int key, int x, int y){
GLfloat stepSize = 0.025f;
if (key == GLUT_KEY_UP) {
yPos += stepSize;
}
if (key == GLUT_KEY_DOWN) {
yPos -= stepSize;
}
if (key == GLUT_KEY_LEFT) {
xPos -= stepSize;
}
if (key == GLUT_KEY_RIGHT) {
xPos += stepSize;
}
//碰撞检测
if (xPos < (-1.0f + blockSize)) {
xPos = -1.0f + blockSize;
}
if (xPos > (1.0f - blockSize)) {
xPos = 1.0f - blockSize;
}
if (yPos < (-1.0f + blockSize)) {
yPos = -1.0f + blockSize;
}
if (yPos > (1.0f - blockSize)) {
yPos = 1.0f - blockSize;
}
glutPostRedisplay();
}
RenderScene函数
//开始渲染
void RenderScene(void)
{
//1.清除一个或者一组特定的缓存区
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
//1.设置颜色RGBA
GLfloat vRed[] = {1.0f, 0.5f, 0.0f, 1.0f};
//定义矩阵
M3DMatrix44f mTransformMatrix;
//平移矩阵
m3dTranslationMatrix44(mTransformMatrix, xPos, yPos, 0.0f);
//当单元着色器不够用时,使用平面着色器
//参数1:存储着色器类型
//参数2:使用什么矩阵变换
//参数3:颜色
shaderManager.UseStockShader(GLT_SHADER_FLAT, mTransformMatrix, vRed);
//提交着色器
triangleBatch.Draw();
glutSwapBuffers();
}
网友评论