4
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .