Search code examples
openglvertexnormals

How to calculate vertex normals of a cylinder?


I have the following cylinder, I am drawing a worm in opengl and I want to calculate the vertex normals.

enter image description here


Solution

  • Calculate normals for every face (triangle) and save it somewhere. Now for every vertex you have several faces that share the vertex (typicaly 6 on your picture). Your final vertex normal is an average of the faces' normals. For 6 faces, you calculate:

    int faceCount = 6;
    float sum = 0.0f;
    for(int face = 0; face < faceCount; ++face)
        sum += faceNormals[face].x;
    normal.x = sum / faceCount;
    // and so on for y and z
    

    Don't forget to normalize the resulting vector, so that its length is 1.

    NOTE: Don't put faceNormals in an array like this. In a real code you probably want to have a single vector-like container of all normals and some logic saying which normals are relevant for which vertex.