简体   繁体   中英

Running code repeatedly while key pressed in JavaScript

I am trying to create a game in JavaScript with THREE.js. I am currently trying to figure out how to properly process keyboard input.

I have already tried a few ways to detect and process keyboard events so that my game properly responds to key down and up events immediately, however my attempts seem to cause a huge performance hit or delay.

 window.addEventListener('keydown', onKeypress); function onKeypress(event) { switch (event.key) { case "ArrowUp": //Code to execute break; case "ArrowDown": //Code to execute break; case "ArrowLeft": //Code to execute break; case "ArrowRight": //Code to execute break; } } 

I would like this to be a continuous and smooth loop while the key is pressed, but instead I only receive one keydown event and then a few seconds later I get the repeated keys. Does anyone know how I could do this in such a way that I get a continuous smooth stream of the function being called?

Rest of code here

One approach would be to store the state of keys currently pressed by the user in a variable outside of the keydown event listener:

/* A map that stores real-time "press state" for corresponding key */
const currentKeysPressed = {};

function onKeypress(event) {

  /* Update keys pressed state for event.key to true
  signifiying the key that caused the event is now pressed */
  currentKeysPressed[event.key] = true;

  /*
  Current code unlikely to be needed:

  switch (event.key) {
    case "ArrowUp":
      //Code to execute
      break;
    case "ArrowDown":
      //Code to execute
      ...
      ...
  }
  */
}

/* Defined new event listener to reset key state
on key release */
function onKeyUp(event) {

  currentKeysPressed[event.key] = false;
}

window.addEventListener('keydown', onKeypress);
window.addEventListener('keyup', onKeyUp);

With something like the above in place, you would then update your applications render loop (and/or code where immediate response to to key state is required) so that key processing logic happens there instead.

So for instance, you might access the currentKeysPressed state in your applications render loop to move the player's game character by doing something along the lines of:

/* Example application loop for your app based on a typical threejs 
application loop */
function updateLoop() {

  if(currentKeysPressed['ArrowUp']) {
      /* Arrow up was just pressed, or is being held down by user */

      /* player.takeStepForward(); */
  }

  /* Draw the scene */
  renderer.render(scene, camera);

  /* Schedule next frame for rendering */
  requestAnimationFrame(update);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM