Making the OpenGL Calls
To draw a tile in OpenGL, you draw a texture-mapped quadrilateral. Before you draw, you must make three OpenGL calls. Call glEnable() to turn on texture mapping. Call glTexEnvf() to tell OpenGL how to draw the texture. For tiles you want to use the mode GL_REPLACE. This mode tells OpenGL to draw the tile, overwriting what was previously on the screen. Call glBindTexture() to bind the texture so you can draw it.
glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBindTexture(GL_TEXTURE_2D, textureName);
After you make the setup calls, call glBegin() to start drawing the quadrilateral.
Each quadrilateral has four vertices. For each vertex you must specify a texture coordinate and a screen coordinate. Call glTexCoord2f() to specify the texture coordinate, and call glVertex3f() to specify where the vertex is on the screen. glVertex3f() takes three arguments: x, y, and z. Use a z value of 0 for 2D drawing.
The values you pass to glTexCoord2f() and glVertex3f() depend on how you store the tiles in the texture and how you set up the orthographic projection. The following code draws the upper left corner of tile number 10 in the ongoing example in this article:
glTexCoord2f(.25, .125); glVertex3f(0.0, 30.0, 0.0);
Here’s the code for the other three corners.
// Upper right corner glTexCoord2f(.375, .125); glVertex3f(1.0, 30.0, 0.0); // Lower right corner glTexCoord2f(.375, .25); glVertex3f(1.0, 29.0, 0.0); // Lower left corner glTexCoord2f(.25, .25); glVertex3f(0.0, 29.0, 0.0);
The order in which you specify the four corners of the tile is very important. Pick one corner and move either clockwise or counterclockwise to draw the other corners. If you crisscross, say drawing the lower left corner after the upper right corner, the drawing will get messed up.
After giving the four vertices texture and screen coordinates, call glEnd() to stop drawing.
Drawing tiles with OpenGL isn’t too difficult. Store a set of tiles in a texture map. Draw a texture-mapped quadrilateral to draw the tile on the screen. Specify the texture coordinate and screen coordinate for each of the quadrilateral’s four vertices.
The sample code that accompanies this article loads a game level on the screen. It provides a relatively simple example of an OpenGL 2D tile engine. Use the arrow keys to scroll around the level.
Previous (Drawing a Tile)