2

I was wondering if anyone could help me figure out how to add a light source to my 3D objects. I have four objects that are rotating and I want the light source to be at a fixed position, and I want to be able to see lighting on the object.

I tried doing this (********):

//*******Initializing the light position
GLfloat pos[] = {-2,4,5,1};

void display() {
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
   glMatrixMode(GL_MODELVIEW);   

   //*******adding the light to the display method
   glLoadIdentity();
   glLightfv(GL_LIGHT0, GL_POSITION, pos);

   // rectangle
   glPushMatrix();
   glTranslatef(0.0f, 2.5f, -8.0f);  
   glRotatef(angleRectangle, 0.0f, 1.0f, 0.0f);  
   drawRectangle();
   glPopMatrix();

   //small cylinder
   glPushMatrix();
   glTranslatef(0.0f, 2.0f, -8.0f);  
   glRotatef(90, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 0.0f, 1.0f);
   drawCylinder(0.2, 0.7);
   glPopMatrix();

   //big cylinder
   glPushMatrix();
   glTranslatef(0.0f, 1.5f, -8.0f); 
   glRotatef(90, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 0.0f, 1.0f);
   drawCylinder(0.7, 2.7);
   glPopMatrix();

   //pyramid
   glPushMatrix();
   glTranslatef(0.0f, -2.2f, -8.0f);  
   glRotatef(180, 1, 0, 0);
   glRotatef(anglePyramid, 0.0f, 1.0f, 0.0f);  
   drawPyramid();
   glPopMatrix();

   glutSwapBuffers(); 

   anglePyramid += k * 0.2f;  //- is CW, + is CCW
   angleRectangle += -k * 0.2f;

}

//******* Then i added these to the main method
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

However when I do this and I run the entire program, my objects turn gray, and at certain points in the rotation they turn white. And this isnt what I want. I want to keep my colorful objects, but I want to be able to see the light source on them.

Any help would be greatly appreciated. Also let me know if you need to see more of my code to figure out the issue. Thanks

4

1 回答 1

3

启用照明 ( GL_LIGHTING) 时,颜色取自材质参数 ( glMaterial)。

如果您仍想使用当前颜色,则必须启用GL_COLOR_MATERIAL 并设置颜色材料参数 ( glColorMaterial):

glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

另请参阅基本 OpenGL 光照


但请注意,按glBegin/glEnd序列绘制,固定函数管道矩阵堆栈和每个顶点光模型的固定函数管道,几十年来已被弃用。阅读Fixed Function Pipeline并查看Vertex Specification and Shader了解最先进的渲染方式。

于 2018-12-03T05:59:57.783 回答