Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm trying to light up a simple 2d triangle with my cursor as a diffuse light source but can't seem to set the normal correctly for the lighting to look right. The function that calculates the normal (m3dFindNormal) comes from the OpenGL Superbible (math3d.h) which takes 3 points on a plane and determines the cross product of 2 vectors from those points. Since this doesn't return a normal of length 1 I then call m3dNormalizeVector3 to get a normal vector of length 1. I then set the normal for the triangle using glNormal to that vector and draw the triangle. Using this code the triangle never lights up at all but when I comment out the glNormal call it lights up on the vertices so something must be wrong with the normal.

glShadeModel(GL_SMOOTH);
GLfloat diffuseLight[] = {0.9f, 0.9f, 0.9f, 1.0f};
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
GLfloat lightPos[] = { x, y, 1.0f, 1.0f }; //x and y are the cursor's position
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glColor3f(0.75f, 0.75f, 0.75f);
glBegin(GL_TRIANGLES);
    M3DVector3f vPoints[3] = {{ SCREEN_WIDTH / 2 - 40, SCREEN_HEIGHT / 2 + 40, 0},
                              { SCREEN_WIDTH / 2 + 40, SCREEN_HEIGHT / 2 + 40, 0},
                              { SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0}};
    m3dFindNormal(vNormal, vPoints[0], vPoints[1], vPoints[2]);
    m3dNormalizeVector3( vNormal );
    glNormal3fv(vNormal);
    glVertex3fv( vPoints[0] );
    glVertex3fv( vPoints[1] );
    glVertex3fv( vPoints[2] );
glEnd();

I know the light works because things light up when I move the cursor around but they light up at the wrong times. Anyone know what I'm doing wrong?

share|improve this question
add comment

closed as too localized by Sam Hocevar, Sean Middleditch, bummzack, Laurent Couvidou, Byte56 Feb 26 '13 at 14:07

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 3 down vote accepted

This was calculating a normal vector of {0,0,-1.0f} instead of {0,0,1.0f} and my light was placed on the positive z-axis. Simply changing the light position to be placed at {x,y,-1.0f} instead of {x,y,1.0f} fixed the problem.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.