Question

I'm creating a cuboid in OpenGL using Vertex arrays but my texture seems to have gone a bit wrong.

Heres my code:

float halfW = getW() / 2;
float halfH = getH() / 2;

GLubyte myIndices[]={
    1,   0,   2,        //front
    2,   0,   3,
    4,   5,   7,        //back
    7,   5,   6,
    0,   4,   3,        //left
    3,   4,   7,        
    5,   1,   6,        //right
    6,   1,   2,
    7,   6,   3,        //up
    3,   6,   2,
    1,   0,   5,        //down
    5,   0,   4
};
float myVertices[] = {
    -halfW, -halfH, -halfW,         // Vertex #0
     halfW, -halfH, -halfW,         // Vertex #1
     halfW,  halfH, -halfW,         // Vertex #2
    -halfW,  halfH, -halfW,         // Vertex #3
    -halfW, -halfH,  halfW,         // Vertex #4
     halfW, -halfH,  halfW,         // Vertex #5
     halfW,  halfH,  halfW,         // Vertex #6
    -halfW,  halfH,  halfW          // Vertex #7
};
float myTexCoords[]= {
    1.0, 1.0,           //0
    0.0, 1.0,           //1
    0.0, 0.0,           //2
    1.0, 0.0,           //3
    0.0, 0.0,           //4
    1.0, 0.0,           //5 
    1.0, 1.0,           //6
    0.0, 1.0            //7
};

Heres the problem: enter image description here

The front and back are rendering fine but top, bottom, left and right are skewed.

Where am I going wrong?

Was it helpful?

Solution

Your texture coordinates and vertex indices look are off. Since Vertex #2 (with the coordinates halfW, halfH, -halfW) has texture coordinate (0, 0), Vertex #6 (with the coordinates halfW, halfH, halfW) should not have the texture coordinate (1, 1). What it does is it puts vertices with the texture coordinates (0, 0) and (1, 1) along the same edge and that leads to trouble.

The problem with a cube is that one 2D texture coordinate per vertex is not enough to for mapping a texture onto a cube like this (however you try to put them, you will end up with weird sides).

The solution is to either add extra triangles so that no side share vertices with another side, or look in to Cube Maps where you specify the texture coordinates in 3D (just as the vertices). I would suggest using Cube Maps, since it avoids adding redundant vertices.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top