gpt4 book ai didi

javascript - 在 JavaScript 中按下按键时重复运行代码

转载 作者:行者123 更新时间:2023-11-30 13:59:55 25 4
gpt4 key购买 nike

我正在尝试使用 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 状态,通过执行以下操作来移动玩家的游戏 Angular 色:

/* 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(updateLoop);
}

关于javascript - 在 JavaScript 中按下按键时重复运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com