我正在尝试使用THREE.js用JavaScript创建游戏。我目前正在尝试弄清楚如何正确处理键盘输入。
我已经尝试了几种方法来检测和处理键盘事件,以便我的游戏可以立即正确响应按键按下和按下事件,但是我的尝试似乎会导致巨大的性能下降或延迟。
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;
}
}
我希望这是一个连续且平滑的循环,同时按下按键,但是相反,我只收到一个按键按下事件,然后几秒钟后,我得到了重复的按键。有谁知道我能以这样一种方式来实现连续平滑的调用流的方式吗?
Rest of code here
最佳答案
一种方法是将用户当前按下的键的状态存储在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);
}
关于javascript - 在JavaScript中按下键时重复运行代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56484999/