OpenGL二维漫游C++
时间: 2024-01-25 16:10:14 浏览: 99
3.凸包证明_opengle二维凸包_
以下是一个使用OpenGL实现的C++二维漫游的例子:
```c++
#include <GL/glut.h>
#include <iostream>
using namespace std;
// 定义窗口大小
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
// 定义迷宫大小
const int MAZE_WIDTH = 10;
const int MAZE_HEIGHT = 10;
// 定义迷宫数组
int maze[MAZE_WIDTH][MAZE_HEIGHT] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
// 定义替身位置
float posX = 1.5f;
float posY = 1.5f;
// 定义替身大小
float sizeX = 0.5f;
float sizeY = 0.5f;
// 定义绘制函数
void drawScene() {
// 清空颜色缓存和深度缓存
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 绘制迷宫
for (int i = 0; i < MAZE_WIDTH; i++) {
for (int j = 0; j < MAZE_HEIGHT; j++) {
if (maze[i][j] == 1) {
glColor3f(1.0f, 1.0f, 1.0f);
} else {
glColor3f(0.0f, 0.0f, 0.0f);
}
glBegin(GL_QUADS);
glVertex2f(i, j);
glVertex2f(i + 1, j);
glVertex2f(i + 1, j + 1);
glVertex2f(i, j + 1);
glEnd();
}
}
// 绘制替身
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2f(posX, posY);
glVertex2f(posX + sizeX, posY);
glVertex2f(posX + sizeX, posY + sizeY);
glVertex2f(posX, posY + sizeY);
glEnd();
// 刷新缓存
glutSwapBuffers();
}
// 定义键盘事件处理函数
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 'w':
if (maze[(int)posX][(int)(posY + sizeY + 0.1)] == 0) {
posY += 0.1;
}
break;
case 's':
if (maze[(int)posX][(int)(posY - 0.1)] == 0) {
posY -= 0.1;
}
break;
case 'a':
if (maze[(int)(posX - 0.1)][(int)posY] == 0) {
posX -= 0.1;
}
break;
case 'd':
if (maze[(int)(posX + sizeX + 0.1)][(int)posY] == 0) {
posX += 0.1;
}
break;
}
glutPostRedisplay();
}
// 定义窗口大小变化事件处理函数
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, MAZE_WIDTH, 0, MAZE_HEIGHT);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char **argv) {
// 初始化GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("OpenGL 2D Maze");
// 注册回调函数
glutDisplayFunc(drawScene);
glutKeyboardFunc(keyboard);
glutReshapeFunc(reshape);
// 开始GLUT主循环
glutMainLoop();
return 0;
}
```
阅读全文