Why does my code dividing a 2D array into chunks fail?
- by Borog
I have a 2D-Array representing my world. I want to divide this huge thing into smaller chunks to make collision detection easier.
I have a Chunk class that consists only of another 2D Array with a specific width and height and I want to iterate through the world, create new Chunks and add them to a list (or maybe a Map with Coordinates as the key; we'll see about that).
world = new World(8192, 1024);
Integer[][] chunkArray;
for(int a = 0; a < map.getHeight() / Chunk.chunkHeight; a++)
{
for(int b = 0; b < map.getWidth() / Chunk.chunkWidth; b++)
{
Chunk chunk = new Chunk();
chunkArray = new Integer[Chunk.chunkWidth][Chunk.chunkHeight];
for(int x = Chunk.chunkHeight*a; x < Chunk.chunkHeight*(a+1); x++)
{
for(int y = Chunk.chunkWidth*b; y < Chunk.chunkWidth*(b+1); y++)
{
// Yes, the tileMap actually is [height][width] I'll have
// to fix that somewhere down the line -.-
chunkArray[y][x] = map.getTileMap()[x*a][y*b];
// TODO:Attach to chunk
}
}
chunkList.add(chunk);
}
}
System.out.println(chunkList.size());
The two outer loops get a new chunk in a specific row and column. I do that by dividing the overall size of the map by the chunkSize.
The inner loops then fill a new chunkArray and attach it to the chunk. But somehow my maths is broken here.
Let's assume the chunkHeight = chunkWidth = 64.
For the first Array I want to start at [0][0] and go until [63][63]. For the next I want to start at [64][64] and go until [127][127] and so on. But I get an out of bounds exception and can't figure out why.
Any help appreciated!
Actually I think I know where the problem lies:
chunkArray[y][x] can't work, because y goes from 0-63 just in the first iteration. Afterwards it goes from 64-127, so sure it is out of bounds.
Still no nice solution though :/
EDIT:
if(y < Chunk.chunkWidth && x < Chunk.chunkHeight)
chunkArray[y][x] = map.getTileMap()[y][x];
This works for the first iteration... now I need to get the commonly accepted formula.