简体   繁体   中英

How to add a single texture on a terrain in OpenGL?

Am new to OpenGL. Is it possible to wrap a single image on a terrain?

The below code would generate image tile , but I want to add single tile on entire terrain.

glBindTexture(GL_TEXTURE_2D, land);
for (int z = 0; z < MAP_Z-1; z++)
{

    glBegin(GL_TRIANGLE_STRIP);

    for (int x = 0; x < MAP_X-1; x++)
    {

    glTexCoord2f(0.0f, 0.0f);
    glVertex3f(terrain[x][z][0], terrain[x][z][1], terrain[x][z][2]);

    glTexCoord2f(1.0f, 0.0f);
    glVertex3f(terrain[x+1][z][0], terrain[x+1][z][1], terrain[x+1][z][2]);

        glTexCoord2f(0.0f, 1.0f);
    glVertex3f(terrain[x][z+1][0], terrain[x][z+1][1], terrain[x][z+1][2]);

        glTexCoord2f(1.0f, 1.0f);
        glVertex3f(terrain[x+1][z+1][0], terrain[x+1][z+1][1], terrain[x+1][z+1][2]);

    }
    glEnd();
}

The problem is that you are currently mapping your texture to each square. You need to have your glTexCoord2f change as you go over the terrain. Just divide the x and z coordinates by the width and height of your terrain in the for loop.

for (int z = 0; z < MAP_Z-1; z++)
{

    glBegin(GL_TRIANGLE_STRIP);

    for (int x = 0; x < MAP_X-1; x++)
    {

        glTexCoord2f((float)x/(float)MAP_X, (float)z/(float)MAP_Z);
        ...
        ... // Other code with (x+1) and (z+1) in the glTexCoord2f
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM