2

我正在制作一个简单的画布,用户使用 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的问题吗?任何帮助表示赞赏!

4

1 回答 1

6

您缺少一些您需要的案例陈述。我相信你的一些案例编号也不正确。试试这个可运行的片段:

(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

//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 65: //a
      keyA = true;
      break;
    case 87: //w
      keyW = true;
      break;
  }
}

function onKeyUp(event) {
  var keyCode = event.keyCode;

  switch (keyCode) {
    case 68: //d
      keyD = false;
      break;
    case 83: //s
      keyS = false;
      break;
    case 65: //a
      keyA = false;
      break;
    case 87: //w
      keyW = 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, 800, 800);
  c.fillStyle = "blue";
  c.fillRect(tickX, tickY, 100, 100);

  if (keyD == true) {
    tickX += 1;
  }
  if (keyS == true) {
    tickY += 1;
  }
  if (keyA == true) {
    tickX--;
  }
  if (keyW == true) {
    tickY--;
  }
}
window.requestAnimationFrame(drawStuff);
<!DOCTYPE html>
<html>
<head></head>
<body>
  <canvas id="myCanvas" width='800' height='800'></canvas>
</body>
</html>

于 2013-01-17T23:33:55.980 回答