wasd camera move threejs in javascript

To implement wasd camera movement in Three.js, you can listen for keyboard events and update the camera position accordingly.

Here is an example:

index.tsx
// create a camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

// set initial camera position
camera.position.set(0, 0, 5);

// listen for keyboard events
const keys = {};
document.addEventListener('keydown', event => {
  keys[event.code] = true;
});

document.addEventListener('keyup', event => {
  keys[event.code] = false;
});

// update camera position on each animation frame
function animate() {
  if (keys['KeyW']) {
    camera.position.z -= 0.1;
  }
  if (keys['KeyA']) {
    camera.position.x -= 0.1;
  }
  if (keys['KeyS']) {
    camera.position.z += 0.1;
  }
  if (keys['KeyD']) {
    camera.position.x += 0.1;
  }
  
  requestAnimationFrame(animate);
}

animate();
733 chars
36 lines

In this example, we create a PerspectiveCamera, set an initial position, and then listen for keyboard events using addEventListener. When a key is pressed or released, we update the corresponding entry in the keys object.

Then, on each animation frame, we check the keys object to see which keys are currently pressed and update the camera position accordingly using the position property. Finally, we use requestAnimationFrame to continue the animation loop.

With this implementation, pressing 'w' moves the camera forward, 'a' moves it left, 's' moves it backward, and 'd' moves it right.

gistlibby LogSnag