gpt4 book ai didi

javascript - 在javascript中检测两个键盘按钮

转载 作者:行者123 更新时间:2023-12-02 16:24:42 28 4
gpt4 key购买 nike

我正在编写一个简单的 Canvas 游戏,并且希望能够在屏幕上对 Angular 移动我的 Angular 色。如何检测按下的两个键(例如向上和向右)?这是我到目前为止的代码-

function keyHit(evt){
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (player2y >= 1){
player2y -= 4;
} else {player2y = 0;}
break;
case 40: /* Down arrow was pressed */
if (player2y <= 364){
player2y += 4;
} else { player2y = 365;}
break;
case 37: /* Left arrow was pressed */
if (player2x >= 1){
player2x -= 4;
} else {player2x = 0;}
break;
case 39: /* Right arrow was pressed */
if (player2x <= 665){
player2x += 4;
} else {player2x = 666;}
break;
}
}

最佳答案

捕获“keydown”和“keyup”事件并维护当前按下的按键列表。示例:

pressed = {}


window.onkeydown = function(e) {
pressed[e.keyCode] = 1
handler(Object.keys(pressed).sort())
}

window.onkeyup = function(e) {
delete pressed[e.keyCode];
handler(Object.keys(pressed).sort())
}

function handler(pressed) {
document.getElementById("log").value = pressed
if(pressed == "38,39")
alert("Up+Right pressed!")
}
<textarea id="log"></textarea><br>click here first, then press some keys

关于javascript - 在javascript中检测两个键盘按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28781114/

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