Reputation: 375
I'm having some issues loading some tiles to my game. My game world currently has a pixel size of 770x450. I have loaded a single tile at position (0, 330)
, however I want to make a loop that copies and loads the tile along the x axis until it reaches (770, 330)
. I could simply copy the code and paste the code to load each tile separately but that would be bad code.
Here's my current Initialize()
code:
protected override void Initialize()
{
position = new Vector2(0, 330);
// x axis = 770 pixel
// y axis = 450 pixels
this.IsMouseVisible = true;
base.Initialize();
}
My tile is declared as Texture2D gameTile;
.
Upvotes: 1
Views: 869
Reputation: 159
http://xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:1
That link provides a tutorial that covers most of what you will need to create the tile engine.
It looks like you are creating the tiles inside the Applications Initialize function. You would be better off creating some sort of tile manager that will store all the tiles you need.
In terms of creating the tiles, you could use either an Array of Structures, or Structure of Arrays. For the first one, you would create a Tile class that would store at least the position of the tile. If using a spritesheet to render the tiles, you could also include a TileID to determine which tile should be used to draw.
For the Structure of Arrays, you could store an array of Vectors that will be used for the tiles (inside the Tile Manager), and another array of the TileID. Both methods work. I would probably recommend the first for you though for readability and to practice Object Oriented Programming.
The Texture2D should also be loaded only once. You don't post where you do your loading or how you plan on making more tiles, so I'm assuming your plan was to load the texture2D for each tile, which would be a bad idea.
Finally, in terms of looping, once you have your tile class made, your tile manager or initialize function would loop through to create and set the position for each tile (pseudocode):
int tileRowCount = mapSizeX / tileSizeX;
int tileColumnCount = mapSizeY / tileSizeY;
for(int rowIndex = 0; rowIndex < tileRowCount; rowIndex++)
{
for(int columnIndex = 0; columnIndex < tileColumnCount; columnIndex++)
{
tileList.Add(new Tile(new Vector2(columnIndex * tileSizeX, rowIndex * tileSizeY);
}
}
Then for drawing:
foreach(Tile tile in tileList)
{
///not exact Draw call, not looking at the documents right now
tile.Draw(spriteBatch, tileTexture, tile.Position);
}
That's the gist of what I think you're after. If I'm on the wrong track, let me know I will adapt the answer. I did skip out on some of the more nitty-gritty details, but if you have any issues there is the link and you can ask more.
EDITED: Drawing portion wasn't in code format
Upvotes: 2