Search code examples
c++qtopenglopengl-compattexturing

Applying 2d texture to single cube face with change in z direction in opengl


I am trying to apply a texture to 1 face of a cube, but the problem I have is the cube is in the z direction as well.

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, Tex);
glBegin(GL_POLYGON);
  glTexCoord2f( 1.0, 1.0); glVertex3f( 1.0,  1.0,  1);
  glTexCoord2f( 1.0, -1.0); glVertex3f( 1.0, -1.0,  1);
  glTexCoord2f( 1.0, -1.0); glVertex3f( 1.0, -1.0, -1);
  glTexCoord2f( 1.0, 1.0); glVertex3f( 1.0,  1.0, -1);
glEnd();
glDisable(GL_TEXTURE_2D);

Obviously by doing it this way I end up with repeated texture vertices (1,1) and (1,-1) because they don't include the z axis. How can I resolve this issue?


Solution

  • It is not necessary that the texture coordinates are associated to the x and y component of the vertex coordinates or even have to be the same. The texture coordinates are completely independent.
    You have to define how the 2 dimensional texture is wrapped on a surface in 3 dimensional space. For each side of the cube you've to define individual texture coordinates.

    Chang the texture coordinates. e.g.:

    glBegin(GL_POLYGON);
    
    glTexCoord2f( 1.0,  1.0); glVertex3f( 1.0,  1.0,  1.0);
    glTexCoord2f( 1.0,  0.0); glVertex3f( 1.0, -1.0,  1.0);
    glTexCoord2f( 0.0,  0.0); glVertex3f( 1.0, -1.0, -1.0);
    glTexCoord2f( 0.0,  1.0); glVertex3f( 1.0,  1.0, -1.0);
    
    glEnd();