I have set up a tilemap system, and am rendering it in a way that lets me pan through the map using a camera offset. However, I have discovered it is incredibly inefficient, but am unsure of how I can increase efficiency.
Here is my current rendering code:
float lastCamOffSetX = -1, lastCamOffSetY = -1;
public override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
int count = 0;
int startCol = (int)camOffsetX/world.TileWidth;
int startRow = (int)camOffsetY/world.TileHeight;
int endCol = (int)(startCol + viewPortWidth - (camOffsetX/world.TileWidth));
int endRow = (int)(startRow + viewPortHeight - (camOffsetY/world.TileHeight));
if (startCol < 0) startCol = 0;
if (startRow < 0) startRow = 0;
if (endCol > world.Width) endCol = world.Width;
if (endRow > world.Height) endRow = world.Height;
for (int x = startCol; x < endCol; x++)
{
for (int y = startRow; y < endRow; y++)
{
int screenPosX = (int)((x * world.TileWidth) - (camOffsetX));
int screenPosY = (int)((y * world.TileHeight) - (camOffsetY));
Tile tile = world.Data[x, y];
if (screenPosX >= -1 * world.TileWidth
&& screenPosX <= (viewPortWidth + 1) * world.TileWidth
&& screenPosY >= -1 * world.TileHeight
&& screenPosY <= (viewPortHeight + 1) * world.TileHeight)
{
Color color
= (tile.TileType == TileType.Land ? Color.Green : Color.Blue);
DrawRectangle(spriteBatch, new Rectangle(screenPosX,
screenPosY, world.TileWidth, world.TileHeight), color);
count++;
}
}
}
//Debug.WriteLine(count + " - " + (endCol-startCol)*(endRow-startRow));
spriteBatch.End();
lastCamOffSetX = camOffsetX;
lastCamOffSetY = camOffsetY;
}
private void DrawRectangle(SpriteBatch spriteBatch, Rectangle coords, Color color)
{
var rect = new Texture2D(this.GraphicsDevice, 1, 1);
rect.SetData(new[] { color });
spriteBatch.Draw(rect, coords, color);
}
Currently, I am only drawing tiles which are inside the screen/camera region. How can I improve the efficiency of my script?