javascriptthree.jskeycodegltf

Javascript movement delay on initial keypress (3D)


I want the movement to be smooth upon pressing a key, the object does an initial movement and then starts moving completely when holding down the button.


//movement speed
var xSpeed = 0.5;
var zSpeed = 0.5;

document.addEventListener("keydown", onDocumentKeyDown, false);

function onDocumentKeyDown(event) {
  var keyCode = event.which;
  if (keyCode == 87) {  //W KEY
    car.position.z -= zSpeed;
  } else if (keyCode == 83) {  //S KEY
    car.position.z += zSpeed;
  } else if (keyCode == 65) {  //A KEY
    car.position.x -= xSpeed;
  } else if (keyCode == 68) {  //D KEY
    car.position.x += xSpeed;
  } else if (keyCode == 32) {
    car.position.set(0, 0, 0);
  }
};

Trying to get a GLTF imported model to be controlled on a plane with keyboard controls smoothly. Tried wrapping the program in a loop and made the state of the keyboard available inside the scope of that loop but couldn't get it working


Solution

  • You could try an approach where the velocity is modified upon keyup/keydown, and the loop just modifies the car's position based on the velocity.

    // initial movement speed
    var xSpeed = 0;
    var zSpeed = 0;
    
    document.addEventListener("keydown", onDocumentKeyDown, false);
    document.addEventListener("keydown", onDocumentKeyUp, false);
    
    function onDocumentKeyDown(event) {
      var keyCode = event.which;
      if (keyCode == 87) {  //W KEY
        zSpeed = -0.5;
      } ... // do so for the rest of the keys
    };
    
    
    function onDocumentKeyUp(event) {
      var keyCode = event.which;
      if (keyCode == 87) {  //W KEY
        zSpeed = 0;
      } ... // do so for the rest of the keys
    };
    
    function loop() {
    car.position.z += zSpeed;
    car.position.x += xSpeed;
    window.requestAnimationFrame(loop);
    }
    

    If you are interested in more eased movement, e.g. the car doesn't just start moving at constant velocity but ramps up and slows down, consider having the keyup/keydown modify an acceleration factor, and the loop modifies the velocity.

    This is a good in-depth article by Daniel Shiffman about attempting to represent the real world with code: https://natureofcode.com/book/chapter-1-vectors/