From f300fe1be7eb5f6271daad8c0cf0b3bc8f26f3b2 Mon Sep 17 00:00:00 2001 From: Juan Sebastian Montoya Date: Fri, 13 Sep 2024 16:14:53 -0500 Subject: [PATCH] feat(#6): add basic camera support --- index.html | 2 +- index.js | 60 +++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/index.html b/index.html index 4be9957..d8caa7e 100644 --- a/index.html +++ b/index.html @@ -6,7 +6,7 @@ name="viewport" content="width=device-width, initial-scale=1.0" /> - Baena + Game Engine = height || col >= width) continue; // Omitimos tiles fuera del rango del tilemap - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { if (debug) { - ctx.strokeRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE); + ctx.strokeRect( + (col - cameraX) * TILE_SIZE, + (row - cameraY) * TILE_SIZE, + TILE_SIZE, + TILE_SIZE + ); } - - const tile = data[row * cols + col]; + const tile = data[row * width + col]; ctx.drawImage( levelImage, ((tile - 1) * TILE_SIZE) % levelImage.width, Math.floor(((tile - 1) * TILE_SIZE) / levelImage.width) * TILE_SIZE, TILE_SIZE, TILE_SIZE, - col * TILE_SIZE, - row * TILE_SIZE, + (col - cameraX) * TILE_SIZE, + (row - cameraY) * TILE_SIZE, TILE_SIZE, TILE_SIZE ); @@ -42,6 +53,17 @@ async function drawLevel({ levelName, imageName }) { } } +function moveCamera(dx, dy) { + cameraX = Math.min( + Math.max(cameraX + dx, 0), + Math.floor((320 - canvasResizer.width) / TILE_SIZE) + ); + cameraY = Math.min( + Math.max(cameraY + dy, 0), + Math.floor((240 - canvasResizer.height) / TILE_SIZE) + ); +} + async function run() { await canvasResizer.load(); @@ -65,6 +87,24 @@ async function run() { await drawLevel(selectedLevel); }); + window.addEventListener("keydown", (event) => { + switch (event.key) { + case "ArrowUp": + moveCamera(0, -1); + break; + case "ArrowDown": + moveCamera(0, 1); + break; + case "ArrowLeft": + moveCamera(-1, 0); + break; + case "ArrowRight": + moveCamera(1, 0); + break; + } + drawLevel(selectedLevel); + }); + await drawLevel(selectedLevel); }