我有一个glutSolidTeapot(它的表面法线根据opengl.org自动生成)和一个发出漫射光的光源。当我尝试旋转茶壶时,问题就出现了:它看起来像光源也在旋转,而不是保持在我定义的相同位置(它基本上遵循茶壶)。正如你在我的代码中看到的那样,我只是在初始化时修改了光照位置,所以它不会受到glRotatef()的影响,因为它在之后调用设置光源位置。如何在旋转对象时在OpenGL中注入光源?
尽管花了很多时间试图解决这个问题,我真的不知道这种行为可以归因于什么。
粘贴glEnable(GL_NORMALIZE);在初始化中也没有解决问题。
我认为所需的输出应该是一个有光泽的右侧茶壶(因为光线来自该方向),无论茶壶旋转的角度是多少。
如果您想测试我的代码,请按空格旋转茶壶。
#include <math.h>
#include <stdlib.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
void onInitialization() { //creating the light source
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
GLfloat diffuse[]={0.8, 0.8, 0.8, 1.0};
GLfloat pos[]={0.5, 0.0, 0.8, 0.0};
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_LIGHT0);
glRotatef(-90, 1, 0, 0); //we want to see the top of the teapot
}
void onDisplay() {
glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//rotating on every frame (for testing purposes only)
glRotatef(5, 0,1,0);
glutSolidTeapot(0.4);
glFinish();
glutSwapBuffers();
}
void onKeyboard(unsigned char key, int x, int y) {
if (key==32){ //do rotation upon hitting the Space key
glutPostRedisplay();
}
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Teapot");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
onInitialization();
glutDisplayFunc(onDisplay);
glutKeyboardFunc(onKeyboard);
glutMainLoop();
return 0;
}
我会手动旋转点而不使用glRotate!这会有点烦人,但那会100%解决你的问题。我自己也遇到了这个问题,找不到任何其他解决方案。 – 2012-03-16 06:20:09