Skip to content

Instantly share code, notes, and snippets.

@detain
Created May 12, 2023 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save detain/36373e9e299a6bfd9ce6fb5b85a79c3f to your computer and use it in GitHub Desktop.
Save detain/36373e9e299a6bfd9ce6fb5b85a79c3f to your computer and use it in GitHub Desktop.
adding keyboard movement to three.js

To add WASD keyboard movement support to the webgl_loader_fbx.html file from the Three.js GitHub repository, you can make the following changes:

  1. First, add a controls variable to the JavaScript code near the top of the file, to store the instance of the THREE.OrbitControls object:
var camera, controls;
  1. Next, locate the init() function and add the following code after the camera variable is defined, to instantiate the OrbitControls object and set some initial values:
controls = new THREE.OrbitControls(camera, document.body); controls.target.set(0, 0, 0);
controls.update();
  1. Finally, add an event listener to the document object that listens for keydown events, and updates the camera position based on the current key pressed (W, A, S, or D):
document.addEventListener('keydown', function(event) {
    switch (event.keyCode) {
        case 87: // W
            camera.position.z -= 0.1;
            break;
        case 65: // A
            camera.position.x -= 0.1;
            break;
        case 83: // S
            camera.position.z += 0.1;
            break;
        case 68: // D
            camera.position.x += 0.1;
            break;
    }
});

These changes should allow you to use the W, A, S, and D keys to move the camera around the scene. You may need to adjust the movement speed or modify the code to fit your specific needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment