JSFiddle - React, Tailwind, and code Playground
by Gwyn Milcote
HTML
In game, tiles are 30x30px. The view is 20 x 14 tiles, and 1 chunk is loaded at a time. The camera stays fixed; when pet leaves the chunk, the next chunk is loaded and pet appears to move into it from above/below/side. So, each chunk is 20 x 14. For simplicity, all maps should be a multiple of those.
<p><div id='chunk_count'></div></p>
<div id='map_chunk'></div>
<br><br>
<div id='whole_map'></div>
JavaScript
let testMap = [];
let chunkWidth = 20;
let chunkHeight = 14;
function generateMap(chunksWide, chunksHigh){
let map = [];
let width = chunkWidth * chunksWide;
let height = chunkHeight * chunksHigh;
for(let y = 0; y < height; y++){
let row = [];
for(let x = 0; x < width; x++){
row.push("y" + (y + 1) + " x" + (x + 1));
}
map.push(row);
}
testMap = map;
}
function renderWholeMap(){
$("#whole_map").html(JSON.stringify(testMap));
}
/*
* Cut out a certain section of the 2D array.
*/
function getChunk(width,height){
// First, divide whole map: how many chunks high/across?
let wide = (testMap.length / chunkHeight);
let high = (testMap[0].length / chunkWidth);
$("#chunk_count").html("This map is " + wide + " chunks wide and " + high + " high.");
// How far down/across to begin? Top left corner of chunk.
let top = (chunkHeight * height) - chunkHeight;
let left = (chunkWidth * width) - chunkWidth;
// Loop down rows, slice part of each row.
let temp = [];
for(let i = 0; i < chunkHeight; i++){
let fullRow = testMap[i + top];
let row = fullRow.slice(left, left + chunkWidth);
temp.push(row);
}
// Output for test.
$("#chunk_count").append(" Start from top " + top + ", left " + left);
renderChunk(temp);
}
function renderChunk(chunk){
$("#map_chunk").html(JSON.stringify(chunk));
}
generateMap(2,2);
//renderWholeMap();
getChunk(2,2);