Saturday, June 16, 2012

XNA Tutorial - Basic Tile Engine

Its been a while since my last blog post and tutorial so I thought I'd do another. I have recently been working on a tile based game and found them very interesting so I thought I'd do a tutorial on a really basic tile engine and expand on it in future blog posts.

First of all you will need to download the graphics pack here. These are just really basic examples of tiles you might find in a tile engine.

In Visual Studio create a new windows game and call it SimpleTileEngine. I like to remove all the comments in the Game1 class. I find it makes my code look messy.

For our tile engine we will use a 2 dimensional array of ints. This is the easiest way to represent a tile engine. While were at it we will also create a list of tile textures.
We will use tileWidth and tileHeight to calculate the position of tiles later in the draw method.

Next we need to initialize our variables.
We load our textures into a list of textures and initialize 2D array of ints. You can see there are different numbers in the array. These numbers directly correspond to the index of that texture in the list of textures. As long as you don't have a number that is larger than the amount of textures in the list of textures it should work fine.

We don't need anything in the update method all our work from here is in the draw. In the draw we need to loop through each tile in the tile array to draw them. In a 2D array the Y value that you see in the code below is actually the row number. We get this number by calling tileMap.GetLength(0). The X is the index of a number in that row like a column. This is reason the x and y are mixed up in the line tiles[tileMap[y, x]]. tileMap[y, x] returns the number in the row y and column x which corresponds to the index of the texture in the textures array as explained above. To get the correct position to draw the tile we need to use the tileWidth and tileHeight we declared above.

After that were finished. Press F5 to run and you should see this.
You can increase the amount of tiles that are drawn by just increasing the size of the array just like below.

It should look bigger like this

Download the finished solution here.

Were pretty much finished. I hope you found it enjoying. If you have any questions or spot an error let m know in the comments below.

1 comment: