Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm creating a game using Pixi.js and have decided that the best way to present a map is to "chunk" it in to 16x16 tile sections and render each when needed - I'm having a bit of trouble parsing an array and separating it in to chunks.

For example, I have a 400x400 tile map in an array (Which is 160,000 array items). I want to split that up in to 25x25 chunks, each chunk having 16x16 tiles in it.

The code I have now works almost perfectly; it generates the 625 chunks (25x25) and almost gets the tiles correctly. My code is as follows (It's not part of my game, it's just being used to test chunk logic):

var countY = 0,
    tileX = 0,
    tileY = 0,
    chunkLength = 16,
    totalTiles = 400,
    chunks = Math.floor(totalTiles / chunkLength),
    chunkCountX = 0,
    chunkCountY = 0,
    tiles = [ ];

/* Generate Tiles Array */
for(var x = 0; x < (totalTiles * totalTiles); x++) {
    tiles[x] = x;
}

var str = ''; // Debug

/* Start Chunking */
for(var t = 0; t < tiles.length; t++) {
    var id = tiles[((tileY * totalTiles) + (tileX + (chunkCountX * chunkLength)))];
    str += id + ','; // Debug

    if(tileX >= (chunkLength - 1)) {
        str += '\n'; // Debug

        if(countY >= (chunkLength - 1)) {
            console.log('- Chunk X #' + chunkCountX + ' Chunk Y #' + chunkCountY + ' -'); // Debug
            console.log(str); // Debug
            str = ''; // Debug

            if(chunkCountY >= (chunks - 1)) {
                chunkCountY = 0;
                chunkCountX++;
                tileY = 0;
            }else{
                chunkCountY++;
            }

            countY = 0;
        }else{
            tileY++;
            countY++;
        }

        tileX = 0;
    }else{
        tileX++;
    }
}

If you run this, you'll see that the output starts like the following:

http://i.imgur.com/GsDXSDL.png

This is perfectly fine apart from each new chunk starts on the same row as the previous chunk finished on. (In this case, Chunk X #0 Chunk Y #0 ends with 6000,6001,6002... and Chunk X #0 Chunk Y #1 starts with the same). This isn't right; the next chunk should carry on the sequence and start on the row after that.

share|improve this question
    
Maybe you can outline more what you intend to do with the chunking? I read over you question and it seems that you are having a more general programming question on how to divide a 2d array in several sub-arrays then related to game development. Wouldn't you just simple take the [n*16]th to [(n+1)*16]th element out in two nested for loops? –  Benedikt S. Vogler May 11 at 9:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.