about summary refs log tree commit diff stats
path: root/js/canvas/game.js
diff options
context:
space:
mode:
Diffstat (limited to 'js/canvas/game.js')
-rw-r--r--js/canvas/game.js51
1 files changed, 28 insertions, 23 deletions
diff --git a/js/canvas/game.js b/js/canvas/game.js
index 7b02bde..e8ef51f 100644
--- a/js/canvas/game.js
+++ b/js/canvas/game.js
@@ -13,7 +13,7 @@ ctx.fillStyle = "#e0f8cf";
 ctx.fillRect(0, 0, canvas.width, canvas.height);
 
 // create a rectangle
-const rect = {
+const player = {
   x: 50,
   y: 50,
   width: 16,
@@ -23,62 +23,67 @@ const rect = {
   colorAlt: "pink"
 };
 
-// draw the rectangle
-ctx.fillStyle = rect.color;
-ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
-
-// move the rectangle
-rect.x += 5;
-
-// clear the canvas
-ctx.clearRect(0, 0, canvas.width, canvas.height);
-
-// draw the rectangle
-ctx.fillStyle = rect.color;
-ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
-
 // add keyboard input
+// FIXME: this input is blocking, allowing for only 1 key to be read at a time
+// this means that if you wanna do 2 things at 1 time you cannot.
+// For more info, <https://medium.com/@dovern42/handling-multiple-key-presses-at-once-in-vanilla-javascript-for-game-controllers-6dcacae931b7>
 document.addEventListener("keydown", (event) => {
   switch (event.code) {
     case "ArrowLeft":
     case "KeyH":
     case "KeyA":
-      rect.x -= rect.step;
+      player.x -= player.step;
       break;
     case "ArrowRight":
     case "KeyL":
     case "KeyD":
-      rect.x += rect.step;
+      player.x += player.step;
       break;
     case "ArrowUp":
     case "KeyK":
     case "KeyW":
-      rect.y -= rect.step;
+      player.y -= player.step;
       break;
     case "ArrowDown":
     case "KeyJ":
     case "KeyS":
-      rect.y += rect.step;
+      player.y += player.step;
       break;
     case "KeyZ":
     case "KeyN":
-      rect.color = "#65ff00";
+      player.color = "#65ff00";
       break;
     case "KeyX":
     case "KeyM":
-      rect.color = rect.colorAlt;
+      player.color = player.colorAlt;
       break;
   }
 });
 
+
 // game loop
 function gameLoop() {
   // clear the canvas
   ctx.clearRect(0, 0, canvas.width, canvas.height);
 
+  // looping canvas space
+  // this feels like a hack...
+  if (player.x < 0) {
+    player.x = canvas.width - 1
+  }
+  if (player.x > canvas.width) {
+    player.x = 1
+  }
+  if (player.y < 0) {
+    player.y = canvas.height - 1
+  }
+  if (player.y > canvas.height) {
+    player.y = 1
+  }
+
   // draw the rectangle
-  ctx.fillStyle = rect.color;
-  ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
+  ctx.fillStyle = player.color;
+  ctx.fillRect(player.x, player.y, player.width, player.height);
 
   // request the next frame
   requestAnimationFrame(gameLoop);