1.源码实现
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <cmath>
using namespace std;
float angleX = 0;
float angleY = 0;
void drawTriangle()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
float cameraPos[] = {0.0, 0.0, 0.0};
float lookat[] = {0.0, 0.0, 0.0};
float dist = 0.0;
lookat[0] = -1.0 * sin(angleY * M_PI / 180) * cos(angleX * M_PI / 180);
lookat[1] = 1.0 * sin(angleX * M_PI / 180);
lookat[2] = -1.0 * cos(angleY * M_PI / 180) * cos(angleX * M_PI / 180);
dist = sqrt(lookat[0]*lookat[0]+lookat[1]*lookat[1]+lookat[2]*lookat[2]);
gluLookAt(0.0, 0.0, 0.0, lookat[0]/dist, lookat[1]/dist, lookat[2]/dist, 0, 0.0, 1.0);
//gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0, 1.0, 0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.8, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.8, 0.8);
glEnd();
glutSwapBuffers();
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch(key)
{
case 'q':
case 27:
exit(0);
break;
case 'w':
angleY += 5;
break;
case 's':
angleY -= 5;
break;
case 'a':
angleX += 5;
break;
case 'd':
angleX -= 5;
break;
}
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(400, 400);
glutCreateWindow("hello");
glutKeyboardFunc(keyboardFunc);
glutDisplayFunc(&drawTriangle);
glutMainLoop();
return 0;
}
2.编译源码
$ g++ -o example example.cpp -std=c++11 -lGL -lglut -lGLU
3.运行结果