OpenGL normals misunderstanding?

2019-09-06 12:28发布

问题:

I'm trying to get my lighting to work in OpenGL, using LWJGL as an implementation library. The problem I think I'm having, is that I don't set my normals properly and therefore the lighting doesn't work at certain angles. Here is the code for the cube I'm testing on:

glBegin(GL_QUADS);

glColor3f(r,g,b);

glNormal3f(position.x, position.y, position.z - radius - 0.1f);
glVertex3f(position.x + radius, position.y + radius, position.z - radius);
glVertex3f(position.x + radius, position.y - radius, position.z - radius);
glVertex3f(position.x - radius, position.y - radius, position.z - radius);
glVertex3f(position.x - radius, position.y + radius, position.z - radius);

glNormal3f(position.x, position.y, position.z + radius + 0.1f);
glVertex3f(position.x + radius, position.y + radius, position.z + radius);
glVertex3f(position.x + radius, position.y - radius, position.z + radius);
glVertex3f(position.x - radius, position.y - radius, position.z + radius);
glVertex3f(position.x - radius, position.y + radius, position.z + radius);

glNormal3f(position.x - radius - 0.1f, position.y, position.z);
glVertex3f(position.x - radius, position.y + radius, position.z + radius);
glVertex3f(position.x - radius, position.y - radius, position.z + radius);
glVertex3f(position.x - radius, position.y - radius, position.z - radius);
glVertex3f(position.x - radius, position.y + radius, position.z - radius);

glNormal3f(position.x + radius + 0.1f, position.y, position.z);
glVertex3f(position.x + radius, position.y + radius, position.z + radius);
glVertex3f(position.x + radius, position.y - radius, position.z + radius);
glVertex3f(position.x + radius, position.y - radius, position.z - radius);
glVertex3f(position.x + radius, position.y + radius, position.z - radius);

glNormal3f(position.x, position.y - radius - 0.1f, position.z);
glVertex3f(position.x + radius, position.y - radius, position.z + radius);
glVertex3f(position.x - radius, position.y - radius, position.z + radius);
glVertex3f(position.x - radius, position.y - radius, position.z - radius);
glVertex3f(position.x + radius, position.y - radius, position.z - radius);

glNormal3f(position.x, position.y + radius + 0.1f, position.z);
glVertex3f(position.x + radius, position.y + radius, position.z + radius);
glVertex3f(position.x - radius, position.y + radius, position.z + radius);
glVertex3f(position.x - radius, position.y + radius, position.z - radius);
glVertex3f(position.x + radius, position.y + radius, position.z - radius);

glEnd();

回答1:

Normal vectors are relative to the vertex itself and are always normalized (ie: they have length one).

So, a line like this:

glNormal3f(position.x, position.y, position.z - radius - 0.1f);

Should be replaced by:

glNormal3f(0.0f, 0.0f, 1.0f);