我正在尝试使用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;
}
}
我希望在按下键时这是一个连续且平滑的循环,但是相反,我只收到一个按键按下事件,然后在几秒钟后我得到重复的按键。有人知道我该怎么做才能使调用的函数连续不断地流过吗?
答案 0 :(得分:2)
一种方法是将用户当前按下的键的状态存储在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);
}