我正在编写一个简单的画布游戏,希望能够在屏幕上对角移动我的角色。我如何检测按下的两个键说对了?
到目前为止,这是我的代码-

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

10-06 15:52