函数的原型如下:
gluLookAt(GLdouble eyex,GLdouble eyey,GLdouble eyez,GLdouble centerx,GLdouble centery,GLdouble centerz,GLdouble upx,GLdouble upy,GLdouble upz);
前三个参数的含义是摄像机的位置,四到六个参数是被观察物体的方向,最后面的三个参数是垂直于摄像机向上的向量(也就是摄像机可以扭个角度在同一位置,看同一个地方)
c++实现
#include <iostream>
#include <cstring>
#include <GL/glut.h>
#include <cmath>
using namespace std;
struct point
{
GLdouble x, y, z;
point()
{
x = y = z = 0;
}
point(GLdouble _x, GLdouble _y, GLdouble _z)
{
x = _x;
y = _y;
z = _z;
}
};
typedef point Vector;
void Normalize( Vector &V)
{
GLdouble tmp = sqrt(V.x*V.x + V.y*V.y + V.z*V.z);
V.x = V.x / tmp;
V.y = V.y / tmp;
V.z = V.z / tmp;
}
Vector Cross(Vector a, Vector b)
{
return Vector(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
}
void MyLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ)
{
GLdouble Mat[16];
memset(Mat, 0, sizeof(Mat));
Mat[15] = 1;
Vector forward(centerX - eyeX, centerY - eyeY, centerZ - eyeZ);
Vector up(upX, upY, upZ);
Normalize(forward);
Vector side = Cross(forward, up);
Normalize(side);
up = Cross(side, forward);
Mat[0] = side.x;
Mat[4] = side.y;
Mat[8] = side.z;
Mat[1] = up.x;
Mat[5] = up.y;
Mat[9] = up.z;
Mat[2] = -forward.x;
Mat[6] = -forward.y;
Mat[10] = -forward.z;
cout<<Mat[10]<<" ";
cout<<endl;
glLoadMatrixd(Mat);
glTranslated(-eyeX, -eyeY, -eyeZ);
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0); //背景黑色
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0); //画笔白色
glLoadIdentity(); //加载单位矩阵
// gluLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
MyLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glutWireTeapot(2);
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// gluLookAt(0, 0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
//
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}