这是一个简单的使用OpenGL绘制三维瓦片地图的示例代码:
```
#include <GL/glut.h>
// 地图大小
const int mapWidth = 10;
const int mapHeight = 10;
// 瓦片大小
const float tileSize = 1.0f;
// 高度图数据
float heightMap[mapWidth][mapHeight] = {
{ 1.0f, 2.0f, 3.0f, 4.0f, 3.0f, 2.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f },
{ 3.0f, 4.0f, 5.0f, 5.0f, 5.0f, 4.0f, 3.0f, 3.0f, 3.0f, 3.0f },
{ 4.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 4.0f, 4.0f, 4.0f, 4.0f },
{ 3.0f, 4.0f, 5.0f, 5.0f, 5.0f, 4.0f, 3.0f, 3.0f, 3.0f, 3.0f },
{ 2.0f, 3.0f, 4.0f, 5.0f, 4.0f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f },
{ 1.0f, 2.0f, 3.0f, 4.0f, 3.0f, 2.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ 1.0f, 2.0f, 3.0f, 4.0f, 3.0f, 2.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ 1.0f, 2.0f, 3.0f, 4.0f, 3.0f, 2.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ 1.0f, 2.0f, 3.0f, 4.0f, 3.0f, 2.0f, 1.0f, 1.0f, 1.0f, 1.0f }
};
void display() {
// 清空屏幕
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 设置相机位置
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-mapWidth / 2.0f, -mapHeight / 2.0f, -mapHeight * 2.0f);
// 绘制地图
for (int x = 0; x < mapWidth - 1; x++) {
glBegin(GL_TRIANGLE_STRIP);
for (int y = 0; y < mapHeight; y++) {
// 计算瓦片高度
float h1 = heightMap[x][y];
float h2 = heightMap[x+1][y];
// 绘制瓦片
glColor3f(h1 / 5.0f, h1 / 5.0f, h1 / 5.0f);
glVertex3f(x * tileSize, y * tileSize, h1);
glColor3f(h2 / 5.0f, h2 / 5.0f, h2 / 5.0f);
glVertex3f((x + 1) * tileSize, y * tileSize, h2);
}
glEnd();
}
// 刷新屏幕
glutSwapBuffers();
}
void reshape(int width, int height) {
// 设置视口大小
glViewport(0, 0, width, height);
// 设置投影矩阵
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)width / (float)height, 0.1f, 100.0f);
}
int main(int argc, char** argv) {
// 初始化GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("OpenGL 3D Tile Map");
// 设置回调函数
glutDisplayFunc(display);
glutReshapeFunc(reshape);
// 启用深度测试
glEnable(GL_DEPTH_TEST);
// 进入主循环
glutMainLoop();
return 0;
}
```
这个示例代码使用了OpenGL的三角形带(`GL_TRIANGLE_STRIP`)来绘制地图,高度图数据存储在二维数组`heightMap`中。在`display`函数中,使用`glBegin`和`glEnd`函数绘制瓦片,并使用`glColor3f`函数设置瓦片颜色。在`reshape`函数中,设置了投影矩阵来控制相机视角。