I am making a test xna game as a learning exercise and I have a small question about using 2d textures. Basically the game is a grid of different 'tiles' which are taken from a text map file. I basically just parse through the file when initializing a level and create a matrix of the different tile types. The level is essentially a tub of wall tiles and spikes. So essentially, there are lots of wall tiles and multiple spike tiles and then lots of empty tiles. However, there are four types of wall tile and spike textures to cover different directions.

My question is what is the best way to load the textures for each of the tile? Do I load individual textures for each tile? i.e when I create a tile, pass it a texture2d which I can draw and load the texture at the same time. This seems like a good way, but then I have to load each tiles texture individually and this seems wasteful.

The other option I can think of is to use a static texture in the tile struct an then simple load this texture as a tile atlas with the different walls and spikes. This way I am only loading a single texture, and then when drawing I just move a rectangle to the area of the appropriate tile within the sprite.

I am not sure which of these ways would be optimal from a performance perspective, or if there is an alternative approach?

Thanks in advanmce


1 Answer 1


Use Dictionary to hold all the textures. Key can be anything you like. I use byte, because my map format is all about bytes. Different bytes in map grid, means different tiles. This way, you don't have to load same texture multiple times or attach texture to tile.

Your map would be something like:

byte[,] Tiles = new byte[5,5] {
    {1, 1, 1, 1, 1},
    {1, 2, 2, 2, 2},
    {1, 1, 2, 3, 3},
    {1, 1, 2, 3, 3},
    {1, 1, 2, 1, 1}

This could and should be in file. Text or XML or something what ever feels comfortable.

Numbers could mean:

  1. Grass tile
  2. Sand tile
  3. Bush tile

Load method would look like:

myGrassTile = this.Content.Load<Texture2D>("grassTile");
mySandTile = this.Content.Load<Texture2D>("sandTile");
myBushTile = this.Content.Load<Texture2D>("bushTile");

TextureDict.Add(2,mySandTile );
TextureDict.Add(3,myBushTile );

Here i link number to match correct texture. So later on, i can just read position from map and pass that number to dictionary and it would return me the correct texture2d.

In draw call, you can just:


 for (int x = 1; x <= 5; x++)
      for (int y = 1; y <= 5; y++)
           //calculate the location of tile.
           //If tiles are 32 pixel width and height, then x * 32 and y * 32 would be
           //correct position.
           spriteBatch.Draw(TextureDict[Tiles[x,y]],new Rectangle(x*32,y*32,32,32), Color.White);


Note This is semipseudo code. Its written in one sit, i have not tested it, but it should show you, how it could be done.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .