我做了一个简单的蛇游戏。它就像一个魅力,但有一个多重按键的错误。
例如,当您要向上方向并同时按下左下或右下时,蛇只是简单地死在同一条线上。
所以这是按键的代码
document.body.addEventListener('keydown', keyDown);
function keyDown(event){
//up
if(event.keyCode == 38){
if(yVelocity == 1)
return;
yVelocity = -1;
xVelocity = 0;
}
//down
if(event.keyCode == 40){
if(yVelocity == -1)
return;
yVelocity = 1;
xVelocity = 0;
}
//left
if(event.keyCode == 37){
if(xVelocity == 1)
return;
yVelocity = 0;
xVelocity = -1;
}
//right
if(event.keyCode == 39){
if(xVelocity == -1)
return;
yVelocity = 0;
xVelocity = 1;
}
}
有没有办法防止多次按键或任何其他方式来防止这种情况?