1

First of all, I am very new to openGL so I don't know all the "basic" stuff yet. I am doing this exercise in a book and I have been able to draw a pyramid but I want to draw a tetrahedron now. But I can't seem to get my head around it. I always end up with weird or incomplete shapes. If I am also not doing anything else right, let me know. This is the code. Any help is appreciated.

    float pt1 = 1.0f;
    float pt2 = 0.0f;
    glBegin(GL_TRIANGLES);
    // Front
    glColor3f(1.0f, 0.0f, 0.0f);     // Red
    glVertex3f(pt2, pt1, pt2);
    glVertex3f(-pt1, -pt1, pt1);
    glVertex3f(pt1, -pt1, pt1);

    // Right
    glColor3f(0.0f, 0.0f, 1.0f);     // Blue
    glVertex3f(pt2, pt1, pt2);
    glVertex3f(pt1, -pt1, pt1);
    glVertex3f(pt1, -pt1, -pt1);

    // Back
    glColor3f(0.0f, 1.0f, 0.0f);     // Green
    glVertex3f(pt2, pt1, pt2);
    glVertex3f(pt1, -pt1, -pt1);
    glVertex3f(-pt1, -pt1, -pt1);

    // Left
    glColor3f(1.0f, 1.0f, 0.0f);       // Yellow
    glVertex3f(pt2, pt1, pt2);
    glVertex3f(-pt1, -pt1, -pt1);
    glVertex3f(-pt1, -pt1, pt1);
    glEnd();
Kofi
  • 45
  • 6

1 Answers1

2

A Tetrahedron consist of 4 vertices:

const float s_8_9 = sqrt(0.8f / 0.9f); // = 0.9428f
const float s_2_9 = sqrt(0.2f / 0.9f); // = 0.4714f
const float s_2_3 = sqrt(0.2f / 0.3f); // = 0.8165f

float vertices[4][3] = {
    { 0.0f,   0.0f,   1.0f },
    { s_8_9,  0.0f,  -1.0f / 3.0f},
    {-s_2_9,  s_2_3, -1.0f / 3.0f},
    {-s_2_9, -s_2_3, -1.0f / 3.0f},
};

The vertices form 4 triangular faces:

int indices[4][3] = {{0, 2, 1},  {0, 3, 2},  {1, 3, 0}, {1, 2, 3}};

Use the vertices and indices to draw the Tetrahedron:

glBegin(GL_TRIANGLES);

// Front
glColor3f(1.0f, 0.0f, 0.0f);     // Red
for (int i = 0; i < 3; i++)
    glVertex3fv(vertices[indices[0][i]]);

// Right
glColor3f(0.0f, 0.0f, 1.0f);     // Blue
for (int i = 0; i < 3; i++)
    glVertex3fv(vertices[indices[1][i]]);

// Back
glColor3f(0.0f, 1.0f, 0.0f);     // Green
for (int i = 0; i < 3; i++)
    glVertex3fv(vertices[indices[2][i]]);

// Left
glColor3f(1.0f, 1.0f, 0.0f);     // Yellow
for (int i = 0; i < 3; i++)
    glVertex3fv(vertices[indices[3][i]]);

Rabbid76
  • 202,892
  • 27
  • 131
  • 174