我正在制作一个简单的画布,用户使用 WASD 分别向上、向左、向下、向右移动一个矩形。动画适用于 S 和 D 键,但是当我尝试使用 a 键时它不起作用,我不知道为什么。下面是我的代码。
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event){
var keyCode = event.keyCode;
switch(keyCode){
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 63: //a
keyA = true;
break;
}
}
function onKeyUp(event){
var keyCode = event.keyCode;
switch(keyCode){
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 63: //a
keyA = false;
break;
}
}
//neccessary variables
var tickX = 10;
var tickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function drawStuff(){
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.clearRect(0,0,500,500);
c.fillStyle = "blue";
c.fillRect(tickX,tickY,100,100);
if(keyD == true){
tickX+=5;
}
if(keyS == true){
tickY+=5;
}
if(keyA == true){
tickX--;
}
}
window.requestAnimationFrame(drawStuff);
这是递减tickX的问题吗?任何帮助表示赞赏!