From ed4a76a8fe639d00689dceddfe755a22cdcfa597 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 19 Jan 2023 08:53:44 -0500 Subject: [PATCH] movement --- public/gl/gl.js | 6 +++++ public/test.js | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/public/gl/gl.js b/public/gl/gl.js index 20b6225..ca0dbe6 100644 --- a/public/gl/gl.js +++ b/public/gl/gl.js @@ -10,9 +10,15 @@ export { Mat4 } from './math/Mat4.js' export { Vec2 } from './math/Vec2.js' export { Vec3 } from './math/Vec3.js' export { Loop } +export { DT } +var DT = 0; +var last = Date.now() const Loop = (fn) => { const callback = () => { + var now = Date.now() + DT = ( now - last) / 1000 + last = now fn() window.requestAnimationFrame(callback) } diff --git a/public/test.js b/public/test.js index 65e059a..99ddc7f 100644 --- a/public/test.js +++ b/public/test.js @@ -30,7 +30,70 @@ async function main() { GL.Loop(() => { Renderer.draw(Scene, Camera) Cube.rotation.add(a) + updateInputs(Camera) }); } +const clamp = (num, min, max) => Math.min(Math.max(num, min), max); + +const LEFT = 37; +const RIGHT = 39; +const UP = 38; +const DOWN = 40; +const W = 87; +const A = 65; +const S = 83; +const D = 68; +const Q = 81; +const E = 69; +const lookSpeed = 50; +const moveSpeed = 10; +function updateInputs(Camera) { + var rotate = new GL.Vec3(); + if (keys[RIGHT]) rotate.y += 1; + if (keys[LEFT]) rotate.y -= 1; + if (keys[UP]) rotate.x -= 1; + if (keys[DOWN]) rotate.x += 1; + if(rotate.dot(rotate) > Number.EPSILON) { + var normal = rotate.normalize() + console.log(lookSpeed * GL.DT * normal.x, lookSpeed * GL.DT * normal.y) + Camera.rotation.x += lookSpeed * GL.DT * normal.x; + Camera.rotation.y += lookSpeed * GL.DT * normal.y; + Camera.rotation.z += lookSpeed * GL.DT * normal.z; + } + Camera.rotation.x = clamp(Camera.rotation.x, -90, 90) + Camera.rotation.y = Camera.rotation.y % 360 + + const yaw = Camera.rotation.y * (Math.PI/180); + var forward = new GL.Vec3(Math.sin(yaw), 0, Math.cos(yaw)); + var right = new GL.Vec3(forward.z, 0, -forward.x); + var up = new GL.Vec3(0, 1, 0); + + var move = new GL.Vec3(); + if (keys[W]) move.sub(forward) + if (keys[S]) move.add(forward) + if (keys[A]) move.sub(right) + if (keys[D]) move.add(right) + if (keys[Q]) move.sub(up) + if (keys[E]) move.add(up) + + if(move.dot(move) > Number.EPSILON) { + var normal = move.normalize() + Camera.position.x += moveSpeed * GL.DT * normal.x; + Camera.position.y += moveSpeed * GL.DT * normal.y; + Camera.position.z += moveSpeed * GL.DT * normal.z; + } +} + +var keys = {} +function setupInputs() { + document.onkeydown = function(e) { + keys[e.keyCode] = true; + }; + document.onkeyup = function(e) { + keys[e.keyCode] = false; + } +} + +setupInputs() main() \ No newline at end of file