Reputation: 79
So basically, I'm currently making a game and I decided to add in chunks for big maps so that it wouldn't lag. My idea was to have a main 2D array containing all tiles for my map (in integers), and a list of chunks(which are other 2D arrays).
static int[,] map;
static List<int[,]> chunks;
Say my map was 9x9 in tiles and each chunk is 3x3 in tiles. There should be in total 9 chunks within my List of chunks. I've been thinking about this for over a week now and i haven't came up with a solution.
Even a little help will do so much.
Upvotes: 0
Views: 1428
Reputation: 157
you can achieve this using Buffer.BlockCopy and little logic. Check the below code
static void Main(string[] args)
{
int p = 1;
int[,] array = new int[9, 9];
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
array[i, j] = p++;
}
}
GetChunkUsingBlockCopy(array, 3, 3);
}
static List<int[,]> GetChunkUsingBlockCopy(int[,] array, int row, int column)
{
int chunkcount = (array.GetLength(0) * array.GetLength(1)) / (row * column);
List<int[,]> chunkList = new List<int[,]>();
int[,] chunk = new int[row, column];
var byteLength = sizeof(int) * chunk.Length;
for (int i = 0; i < chunkcount; i++)
{
chunk = new int[row, column];
Buffer.BlockCopy(array, byteLength * i, chunk, 0, byteLength);
chunkList.Add(chunk);
}
return chunkList;
}
Hope this helps ! Please do not forget to mark this as Answer if found suitable.
Upvotes: 1
Reputation: 1317
First, encapsulation is your friend. Don't use multi-dimentional arrays directly in your game code, use classes. A class for a map would let you write your game code around a map without thinking of internal details of how you store your chunks. Using a class for a chunk would allow you to handle chunks easily.
Then, you might assign IDs for your chunks. Store chunks in Dictionary, where ID is the key. Map should store chunk IDs. When your map is asked about a tile at some location (x0,y0), you may calculate which chunk this tile belongs to, find an ID for your chunk, obtain the chunk from your chunks dictionary and ask it for that tile.
Upvotes: 1