Jump to content
  • Advertisement
Sign in to follow this  
grizzlebees

Optimizing tiling in XNA

This topic is 2606 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, First off thank you for your time to read this :) Forgive as english is 2nd language.

I am a beginner to XNA and wrote up an application that tiles and works fine. Right now I draw all the tiles even the ones not in the viewport. This is a problem! I would like to make grids that are huge say, 5000x5000 for my editor.
Basically I want to calculate the start x,y and end x,y that my editor viewport can see and only draw those. What is the best way to do this in XNA?

Here is my code currently:

for (int id_z = 0; id_z < GLB_Data.MapSize.Depth; id_z++)
{
for (int id_y = 0; id_y < GLB_Data.MapSize.Height; id_y++)
{
for (int id_x = 0; id_x < GLB_Data.MapSize.Width; id_x++)
{
XNA.Rectangle source_rectangle = new XNA.Rectangle(GLB_Data.TileMap[id_z, id_x, id_y].texture_location.X * GLB_Data.MapSize.TileSize,
GLB_Data.TileMap[id_z, id_x, id_y].texture_location.Y * GLB_Data.MapSize.TileSize,
GLB_Data.MapSize.TileSize, GLB_Data.MapSize.TileSize);

XNA.Rectangle dest_rectangle = Camera.Transform(new XNA.Rectangle(id_x * Camera.ScaledTileSize, id_y * Camera.ScaledTileSize, Camera.ScaledTileSize, Camera.ScaledTileSize));

sprite_batch.Draw(GLB_Data.TilesTexture, dest_rectangle, source_rectangle, XNAGraphics.Color.White);
}
}
}

Share this post


Link to post
Share on other sites
Advertisement
Can't really help with the C# but the basic idea in 2D is:

Imagine you have a camera whose position is the top left of the screen. Call these co-ords (Ox,Oy).

(Ox/TileWidth,Oy/TileHeight) will give you the index into your tilemap for the tile at the top left of the screen. (Ox%TileWidth,Oy%TileHeight) will give you the offset into that tile.

So draw that tile at the top corner of the screen, minus the offset calculated with the modulus, then just loop across from that tile until the number of tiles drawn times the tile width exceeds the width of the screen. Then go onto the next row and continue.


// excuse the C++ and this is untested

int ox,oy; // our camera position

void f()
{
int sx=ox/tile_width;
int sy=oy/tile_height;

int dx=ox%tile_width;
int dy=oy%tile_height;

for(int y=0;y<number_of_vertical_tiles;++y)
{
for(int x=0;x<number_of_horizontal_tiles;++x)
{
int index=map.at(sx+x,sy+y);

draw_tile(index,(x*tile_width)-dx,(y*tile_height)-dy);
}
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!