Один из подходов состоит в том, чтобы сохранить состояние клавиш, которые в данный момент нажаты пользователем, в переменной вне keydown
прослушивателя событий:
/* 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);
При наличии чего-то подобного приведенному выше вы бы затемобновите цикл рендеринга приложений (и / или код, где требуется немедленный ответ на состояние ключа), чтобы логика обработки ключей выполнялась там.
Так, например, вы можете получить доступ к состоянию currentKeysPressed
в своих приложенияхЦикл рендеринга для перемещения игрового персонажа, делая что-то вроде:
/* 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);
}