Skip to content

Instantly share code, notes, and snippets.

@detain
Created May 12, 2023 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save detain/06076429aac354b049933a65e8f8ec79 to your computer and use it in GitHub Desktop.
Save detain/06076429aac354b049933a65e8f8ec79 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.

To add WASD keyboard movement support to the webgl_loader_fbx.html example from Three.js, you need to do the following:

  1. Define variables to store the camera's position and rotation angles:
var camera, scene, renderer;
var controls, clock;
var keyboard = {};
var moveSpeed = 10;
var rotateSpeed = Math.PI / 2;
var cameraPosition = new THREE.Vector3(0, 0, 200);
var cameraRotation = new THREE.Vector3(0, 0, 0);
  1. Update the camera's position and rotation angles based on keyboard input:
function handleKeyboardInput(delta) {
  if (keyboard['W']) {
    cameraPosition.z -= moveSpeed * delta;
  }
  if (keyboard['S']) {
    cameraPosition.z += moveSpeed * delta;
  }
  if (keyboard['A']) {
    cameraRotation.y += rotateSpeed * delta;
  }
  if (keyboard['D']) {
    cameraRotation.y -= rotateSpeed * delta;
  }
  camera.position.copy(cameraPosition);
  camera.rotation.setFromVector3(cameraRotation);
}
  1. Add event listeners to detect keyboard input:
function init() {
  // ...

  // Add event listeners for keyboard input
  window.addEventListener('keydown', function(event) {
    keyboard[event.key] = true;
  });
  window.addEventListener('keyup', function(event) {
    keyboard[event.key] = false;
  });

  // ...
}
  1. Call the handleKeyboardInput() function in the render loop to update the camera position and rotation:
function animate() {
  var delta = clock.getDelta();
  requestAnimationFrame(animate);
  controls.update(delta);
  handleKeyboardInput(delta);
  renderer.render(scene, camera);
}

With these changes, you should be able to move the camera forward and backward with the W and S keys and rotate the camera left and right with the A and D keys. You can adjust the moveSpeed and rotateSpeed variables to change the speed of movement and rotation.

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.To add keyboard movement support to the webgl_loader_fbx.html Three.js example, you can follow these steps:

  1. Add a listener for the keydown event to the document object.
  2. In the event listener function, check for the corresponding key code for each of the WASD keys (ASCII codes: W=87, A=65, S=83, D=68).
  3. Update the camera position based on the key pressed.

Here is an example implementation:

document.addEventListener('keydown', onDocumentKeyDown, false);
function onDocumentKeyDown(event) {
    var keyCode = event.which;
    if (keyCode === 87) { // W key
        camera.position.z -= 1;
    } else if (keyCode === 65) { // A key
        camera.position.x -= 1;
    } else if (keyCode === 83) { // S key
        camera.position.z += 1;
    } else if (keyCode === 68) { // D key
        camera.position.x += 1;
    }
}

Note that this code assumes that camera is the Three.js camera object. You may need to adjust it if you are using a different camera or have other requirements for the movement behavior.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>FBX loader - Three.js</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <style>
      body {
        margin: 0;
        overflow: hidden;
      }
    </style>
  </head>

  <body>
    <script src="https://threejs.org/build/three.js"></script>
    <script src="https://threejs.org/examples/js/loaders/FBXLoader.js"></script>

    <script>
      var container, camera, scene, renderer, controls;
      var clock = new THREE.Clock();
      var moveForward = false;
      var moveBackward = false;
      var moveLeft = false;
      var moveRight = false;
      var moveSpeed = 100;

      init();
      animate();

      function init() {
        container = document.createElement("div");
        document.body.appendChild(container);

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
        camera.position.set(100, 200, 300);

        scene = new THREE.Scene();
        scene.background = new THREE.Color(0xa0a0a0);
        scene.fog = new THREE.Fog(0xa0a0a0, 200, 1000);

        // ground
        var ground = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000), new THREE.MeshPhongMaterial({ color: 0x999999, depthWrite: false }));
        ground.rotation.x = -Math.PI / 2;
        scene.add(ground);

        var grid = new THREE.GridHelper(2000, 20, 0x000000, 0x000000);
        grid.material.opacity = 0.2;
        grid.material.transparent = true;
        scene.add(grid);

        // model
        var loader = new THREE.FBXLoader();
        loader.load("models/fbx/Samba Dancing.fbx", function (object) {
          object.mixer = new THREE.AnimationMixer(object);
          var action = object.mixer.clipAction(object.animations[0]);
          action.play();
          scene.add(object);
        });

        // renderer
        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.outputEncoding = THREE.sRGBEncoding;
        container.appendChild(renderer.domElement);

        // controls
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.enableZoom = true;
        controls.enablePan = false;
        controls.target.set(0, 100, 0);
        controls.update();

        // event listeners
        window.addEventListener("resize", onWindowResize);
        document.addEventListener("keydown", onKeyDown);
        document.addEventListener("keyup", onKeyUp);
      }

      function animate() {
        requestAnimationFrame(animate);

        var delta = clock.getDelta();

        if (moveForward) {
          camera.translateZ(-moveSpeed * delta);
        }
        if (moveBackward) {
          camera.translateZ(moveSpeed * delta);
        }
        if (moveLeft) {
          camera.translateX(-moveSpeed * delta);
        }
        if (moveRight) {
          camera.translateX(moveSpeed * delta);
        }

        controls.update();
        renderer.render(scene, camera);
      }

      function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      }

      function onKeyDown(event) {
        switch (event.keyCode) {
          case 87: // W
            moveForward = true;
            break;
          case 65: // A
            moveLeft = true;
            break;
          case 83: // S
            moveBackward = true;
            break;
          case 68: // D
            moveRight = true;
            break;
        }
      }

      function onKeyUp(event) {
        switch (event.keyCode) {
          case 87: // W
            moveForward = false;
            break;
          case 65: // A
            moveLeft = false;
            break;
          case 83: // S
            moveBackward = false;
            break;
          case 68: // D
            moveRight = false;
            break;
        }
      }
    </script>
  </body>
</html>


To add WASD keyboard movement to the script, you can follow these steps:

  1. Define a Vector3 object to represent the movement direction.
const moveDirection = new THREE.Vector3();
  1. Add an event listener to the window object to detect key presses.
window.addEventListener('keydown', onKeyDown);
  1. Define a onKeyDown function that updates the moveDirection object based on the pressed key.
function onKeyDown(event) {
    switch (event.keyCode) {
        case 87: // W
            moveDirection.z = -1;
            break;
        case 83: // S
            moveDirection.z = 1;
            break;
        case 65: // A
            moveDirection.x = -1;
            break;
        case 68: // D
            moveDirection.x = 1;
            break;
    }
}
  1. Add another event listener to the window object to detect when a key is released.
window.addEventListener('keyup', onKeyUp);
  1. Define a onKeyUp function that resets the moveDirection object when a key is released.
function onKeyUp(event) {
    switch (event.keyCode) {
        case 87: // W
            moveDirection.z = 0;
            break;
        case 83: // S
            moveDirection.z = 0;
            break;
        case 65: // A
            moveDirection.x = 0;
            break;
        case 68: // D
            moveDirection.x = 0;
            break;
    }
}
  1. In the animate function, update the camera position based on the moveDirection object.
function animate() {
    requestAnimationFrame(animate);

    // Update camera position
    const cameraSpeed = 100; // Adjust as needed
    camera.position.x += moveDirection.x * cameraSpeed * delta;
    camera.position.z += moveDirection.z * cameraSpeed * delta;

    const delta = clock.getDelta();
    if (mixer) mixer.update(delta);
    renderer.render(scene, camera);
    stats.update();
}

Note: This code assumes that the camera object is already defined and that the WASD keys should move the camera along the x and z axes. You may need to adjust the camera speed and key codes based on your specific needs.

To add WASD keyboard movement to the webgl_loader_fbx.html example from the three.js library, you can modify the code in the following way:

  1. Declare a moveForward and moveRight variable to track the movement direction:
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
  1. Add event listeners to detect when the WASD keys are pressed:
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
  1. In the onKeyDown function, set the appropriate movement direction variable to true based on the pressed key:
function onKeyDown(event) {
  switch (event.keyCode) {
    case 87: // W
      moveForward = true;
      break;
    case 65: // A
      moveLeft = true;
      break;
    case 83: // S
      moveBackward = true;
      break;
    case 68: // D
      moveRight = true;
      break;
  }
}
  1. In the onKeyUp function, set the appropriate movement direction variable to false based on the released key:
function onKeyUp(event) {
  switch (event.keyCode) {
    case 87: // W
      moveForward = false;
      break;
    case 65: // A
      moveLeft = false;
      break;
    case 83: // S
      moveBackward = false;
      break;
    case 68: // D
      moveRight = false;
      break;
  }
}
  1. In the animate function, update the camera position based on the movement direction variables:
function animate() {
  requestAnimationFrame(animate);

  const delta = clock.getDelta();
  if (mixer) mixer.update(delta);

  // Update camera position based on movement direction
  if (moveForward) camera.translateZ(-10 * delta);
  if (moveBackward) camera.translateZ(10 * delta);
  if (moveLeft) camera.translateX(-10 * delta);
  if (moveRight) camera.translateX(10 * delta);

  renderer.render(scene, camera);
  stats.update();
}

This should allow you to move the camera forward, backward, left, and right using the W, A, S, and D keys respectively.

To add WASD keyboard movement support to the webgl_loader_fbx.html example from the Three.js library, you need to perform the following steps:

  1. Add the necessary event listeners for keydown and keyup events.

  2. Create a variable to store the current state of each movement key (W, A, S, and D).

  3. Modify the animate() function to adjust the camera's position based on the current state of the movement keys.

Here is an example implementation:To add W, A, S, and D keyboard movement to a Three.js script, there are several steps you can take:

  1. Set up a key listener to detect key presses. You can use the addEventListener() method to listen for the keydown and keyup events, and set up an object to keep track of which keys are currently pressed:
var keys = {}; document.addEventListener('keydown', function(event) {
  keys[event.keyCode] = true;
});
document.addEventListener('keyup', function(event) {
  keys[event.keyCode] = false;
});`

1.  Update the camera position based on which keys are currently pressed. You can use the `translateX()` and `translateZ()` methods of the camera object to move it along the X and Z axes, respectively. Here's an example:

`var speed = 0.1; function updateCamera() {
  if (keys[87]) {
    // W key
    camera.translateZ(-speed);
  }
  if (keys[83]) {
    // S key
    camera.translateZ(speed);
  }
  if (keys[65]) {
    // A key
    camera.translateX(-speed);
  }
  if (keys[68]) {
    // D key
    camera.translateX(speed);
  }
}`

1.  Call the `updateCamera()` function in your `render()` loop to update the camera position every frame.

`function render() {
  // render the scene
  updateCamera();
  requestAnimationFrame(render);
}`

By implementing these steps, you should be able to add simple W, A, S, and D keyboard movement to your Three.js script.To add WASD keyboard movement to the three.js script, you can use the `PointerLockControls.js` module from the three.js official examples. Here's an example:

`import * as THREE from './three.js-master/build/three.module.js' import { GLTFLoader } from './three.js-master/examples/jsm/loaders/GLTFLoader.js'
import { PointerLockControls } from './three.js-master/examples/jsm/controls/PointerLockControls.js'

const canvas = document.querySelector('.webgl')
const scene = new THREE.Scene()

const loader = new GLTFLoader()
loader.load('assets/untitled.glb', function (glb) {
  console.log(glb)
  const root = glb.scene;
  root.scale.set(0.01, 0.01, 0.01)

  scene.add(root);
}, function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + "% loaded")
}, function (error) {
  console.log('An error occured')
})

const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(0, 0, 2)
scene.add(light)

// Camera
const sizes = {
  width: window.innerWidth,
  height: window.innerHeight
}
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 1000)
camera.position.z = 1
camera.lookAt(0, 0, 0)
scene.add(camera)

// Pointer lock controls
const controls = new PointerLockControls(camera, canvas)
document.addEventListener("keydown", (e) => {
  if (e.key === "w") {
    controls.moveForward(0.1);
  } else if (e.key === "a") {
    controls.moveRight(-0.1);
  } else if (e.key === "s") {
    controls.moveForward(-0.1);
  } else if (e.key === "d") {
    controls.moveRight(0.1);
  }
});
document.body.addEventListener("click", () => {
  controls.lock();
});

// Renderer
const renderer = new THREE.WebGLRenderer({
  canvas: canvas,
  antialias: true
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

// Animation loop
const tick = () => {
  renderer.render(scene, camera)
  window.requestAnimationFrame(tick)
  controls.update()
}

To add W A S D keyboard movement to the webgl_loader_fbx example in Three.js, you can follow these steps:

  1. Add the PointerLockControls script to your HTML file by adding this line to the <head> section:
<script src="https://threejs.org/examples/jsm/controls/PointerLockControls.js"></script>
  1. Declare the variables controls and clock at the beginning of your JavaScript file:
var controls, clock;
  1. Initialize the controls and clock variables in the init() function by adding the following lines of code:
controls = new THREE.PointerLockControls(camera, document.body);
scene.add(controls.getObject());

clock = new THREE.Clock();
  1. Create a new function called moveCamera() that will handle the keyboard input and update the camera's position based on the input. Here is an example implementation:
function moveCamera(deltaTime) {
  var speed = 500;
  var moveDistance = speed * deltaTime;

  if (keyboard[87]) { // W key
    controls.getObject().translateZ(-moveDistance);
  }
  if (keyboard[83]) { // S key
    controls.getObject().translateZ(moveDistance);
  }
  if (keyboard[65]) { // A key
    controls.getObject().translateX(-moveDistance);
  }
  if (keyboard[68]) { // D key
    controls.getObject().translateX(moveDistance);
  }
}

This function checks for which keys are pressed and updates the camera's position accordingly. In this example implementation, the W key moves the camera forward, the S key moves the camera backward, the A key moves the camera left, and the D key moves the camera right.

  1. Add a keydown event listener to the document object that updates an array called keyboard to keep track of which keys are currently pressed. Here is an example implementation:
var keyboard = {};

document.addEventListener('keydown', function(event) {
  keyboard[event.keyCode] = true;
});

document.addEventListener('keyup', function(event) {
  keyboard[event.keyCode] = false;
});
  1. Finally, in the animate() function, call the moveCamera() function and pass in the elapsed time since the last frame. Here is an example implementation:
function animate() {
  requestAnimationFrame(animate);

  var deltaTime = clock.getDelta();

  moveCamera(deltaTime);

  renderer.render(scene, camera);
}

That's it! With these steps, you should now have W A S D keyboard movement enabled in your webgl_loader_fbx example in Three.js.

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