From de87bd233aa6d55a46d0486138c1f5c1f926f40d Mon Sep 17 00:00:00 2001 From: stitchy Date: Wed, 18 Dec 2024 07:36:23 +0000 Subject: [PATCH] feat: add wasdqe movement --- shader.mjs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/shader.mjs b/shader.mjs index bf104b6..ca398e2 100644 --- a/shader.mjs +++ b/shader.mjs @@ -1,6 +1,8 @@ const CANVAS_WIDTH = 700; const CANVAS_HEIGHT = 700; let TIME = 0; +let camera_pos = [0, 0, 0]; +let camera_rot = [0, 0, 0]; // ** Initialization stuffs ** // @@ -72,7 +74,7 @@ async function initShader() { const tex2_attr = gl.getUniformLocation(program, "uSampler2"); gl.uniform1i(tex2_attr, 1); - return [gl, program]; + return [gl, program, canvas]; } // Compile Shader Function @@ -93,6 +95,28 @@ async function fetch_local(src) { return await res.text(); } +// Update the Camera position +function updateCamera(gl, program) { + if (keymap.get("w")) { + camera_pos[2] += 0.1; + } + if (keymap.get("a")) { + camera_pos[0] += -0.1; + } + if (keymap.get("s")) { + camera_pos[2] += -0.1; + } + if (keymap.get("d")) { + camera_pos[0] += 0.1; + } + if (keymap.get("e")) { + camera_pos[1] += 0.1; + } + if (keymap.get("q")) { + camera_pos[1] += -0.1; + } + const pos = gl.getUniformLocation(program, "camera_pos"); + gl.uniform3fv(pos, camera_pos); // update the canvas function draw(gl, program) { // Create uniform @@ -100,14 +124,13 @@ function draw(gl, program) { TIME += 1 / 60; gl.uniform1f(loc, TIME); + updateCamera(gl, program); + // Draw the frame recursively on next frame gl.drawArrays(gl.TRIANGLES, 0, 6); requestAnimationFrame(() => draw(gl, program)); } -// Initialize the shader -const [gl, program] = await initShader(); - function loadTexture(gl, url, gl_tex) { // Create texture const texture = gl.createTexture(); @@ -136,5 +159,16 @@ function loadTexture(gl, url, gl_tex) { return texture; } +// Initialize the shader +const [gl, program, canvas] = await initShader(); + +// Key Presses +let keymap = new Map(); +document.addEventListener("keydown", function (event) { + keymap.set(event.key, true); +}); +document.addEventListener("keyup", function (event) { + keymap.set(event.key, false); +}); // Update loop draw(gl, program);