Quickly Draw Lots of Tiles by Saving Them to a Texture First
My game is heavily tile based. I use 16x16 tiles for all the foreground images along with 32x32 tiles for a background layer. For most levels in my game, drawing this was fine. But a select few that have a lot of tiles are slow during this process. This is because there are often several hundred tiles that my game has to draw.
Since these tiles only change when a level is first loaded, I determined that I could save a Texture2D representation of all my tiles and then just draw that each iteration through my game rather than looping through all the tiles.
First, I created a Tile class to hold my tiles. It's pretty basic, just location, size, and texture information. I populate each Tile from a file and pass in a character that determines which texture gets assigned to the tile.
public class Tile
{
public enum TileStatus
{
Visble,
Hidden
}
private Texture2D tileTexture;
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
public int TileWidth
{
get;
set;
}
public int TileHeight
{
get;
set;
}
public TileStatus currentStatus
{
get;
set;
}
public Tile(char initialTileID, ContentManager contentManager)
{
TileHeight = 32;
TileWidth = 32;
switch (initialTileID.ToString())
{
case "1":
{
tileTexture = contentManager.Load<Texture2D>("tiles\\GrayTile");
break;
}
case "2":
{
tileTexture = contentManager.Load<Texture2D>("tiles\\MaroonTile");
break;
}
default:
{
tileTexture = null;
break;
}
}
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (this.currentStatus == TileStatus.Visble)
{
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
spriteBatch.Draw(tileTexture, new Rectangle(X, Y, TileWidth, TileHeight), Color.White);
spriteBatch.End();
}
}
}
Additionally I created a collection object so that I could group these tiles together as one and call a single draw method to draw them all.
public class Tiles : System.Collections.ObjectModel.Collection<Tile>
{
public void Draw(SpriteBatch spriteBatch)
{
for (int i = 0; i < this.Count; i++)
{
this[i].Draw(spriteBa
This article has been view 3589 times.
|