开发者

C++ Opengl render part of an image

Let's say i have a method that get a GLuint texture as a parameter and I'd like to render a part of it. Think about a tile set for instance, i want to be able to load a tile set and render parts (tiles) of it when I load my level.

It would be optimal if I somehow would be able to define the height, width, posX and posY in pixel coordinates from the tile set to draw from.

I've been trying for hours now and any help would be appreciated.

Simplified version of how I currently draw a texture:

    void Render::draw(GLuint texture, float posX, float posY, float sizeX, float size开发者_如何学CY) {

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    glAlphaFunc(GL_GREATER,0.1f);

    glBindTexture( GL_TEXTURE_2D, texture );
    glPushMatrix();
    glTranslatef(posX,posY,0);
    glBegin( GL_QUADS );

    //Bottom-left vertex (corner)
    glTexCoord2i( 0, 0);
    glVertex2f( -sizeX,-sizeY);
    //Bottom-right vertex (corner)
    glTexCoord2i( 1, 0);
    glVertex2f(sizeX,-sizeY);
    //Top-right vertex (corner) 
    glTexCoord2i( 1, 1);
    glVertex2f(sizeX,sizeY);
    //Top-left vertex (corner)
    glTexCoord2i( 0, 1);
    glVertex2f( -sizeX,sizeY);

    glEnd();
    glPopMatrix();
    glDisable(GL_BLEND);
}


You do this using glTexCoord function.
For example, if you tileset contains 4 tiles, and you want to display the top left corner[*] tile, you would do something like this:

glTexCoord2f( 0, 0);
glVertex2f( -sizeX,-sizeY);
glTexCoord2f( 0.5, 0);
glVertex2f(sizeX,-sizeY);
glTexCoord2f( 0.5, 0.5);
glVertex2f(sizeX,sizeY);
glTexCoord2i( 0, 0.5);
glVertex2f( -sizeX,sizeY);

[*] I don't remember how the coordinates work exactly, but it is easy to test in you code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜