Home > Enterprise >  Color disappears when light is used in opengl
Color disappears when light is used in opengl

Time:06-12

glLoadIdentity();               
glTranslatef(0.0f   deltaA - deltaD, 0.0f   deltaQ - deltaE, 0.0f   deltaW - deltaS);
glRotatef(_rotate_x, 1, 0, 0);
glRotatef(_rotate_y, 0, 1, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(20, 15, 15);

enter image description here

If I write the code like this, the red color looks good.

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

glLoadIdentity();               
glTranslatef(0.0f   deltaA - deltaD, 0.0f   deltaQ - deltaE, 0.0f   deltaW - deltaS);
glRotatef(_rotate_x, 1, 0, 0);
glRotatef(_rotate_y, 0, 1, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(20, 15, 15);

glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);

enter image description here

But if I use a light like this, it's white. What's the reason?

How can I solve this problem?

CodePudding user response:

See Basic OpenGL Lighting. When lighting (GL_LIGHTING) is enabled, the render color is taken from the material parameters (glMaterial). If you still want to use the current color attribute (set by glColor), you need to enable GL_COLOR_MATERIAL and to set the color material parameters (glColorMaterial):

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  • Related