Drawing a tile on the screen requires the following steps:
2D game levels normally contain an array of numbers, with each number telling you the tile to draw at that location in the game world. Your game is responsible for finding the tile to draw at a specific location in the game world.
Once you get the tile number, you have to find the tile in the texture map. The entire texture map coordinates range from 0 to 1, with (0.0, 0.0) being the upper left corner of the texture and (1.0, 1.0) being the lower right corner. If you weren’t using tiles, drawing the background would be easy. Draw the entire texture map and have it fill the screen.
Tiles make the drawing situation a little more complicated. The texture map contains an entire set of tiles so you can’t just draw the whole texture. You have to find the tile you want to draw so you draw only the part of the texture that contains the tile.
Suppose the texture map holds an 8 by 8 collection of tiles, which you can see in the figure below. Suppose you want to draw tile number 10. It resides in the second row and the third column. Because there are 8 tiles in each row and 8 tiles in each column, you move .125 units to move one tile down or one tile to the right (.125 = 1/8). To draw tile number 10, you would use the following texture coordinates:
Upper left: (.25, .125) Upper right: (.375, .125) Lower right: (.375, .25) Lower left: (.25, .25)
Each texture corner corresponds to an OpenGL vertex. The vertex’s x and y coordinates are where you want the corner to appear on the screen. Suppose you set up the viewing volume to fit 40 tiles horizontally and 30 tiles vertically, and you want to draw tile number 10 in the upper left corner of the screen. You would use the following vertex coordinates:
Upper left: (0.0, 30.0) Upper right: (1.0, 30.0) Lower right: (1.0, 29.0) Lower left: (0.0, 29.0)
In OpenGL the y coordinate increases as you move up the screen. With a screen projection displaying 30 units vertically, 0 is the bottom of the screen, and 30 is the top.
Next (Making the OpenGL Calls)
Previous (Creating the Texture Map)