检测击键混乱

时间:2015-12-05 20:01:24

标签: javascript

我一直对如何使用javascript移动图像感到困惑。任何输入都会有所帮助,我很确定它与addEventListener行有关。该代码应该显示一个可以用w和s和d键控制的图像,但它不会移动。请不要因为草率编码来判断我,我只有14:P

var facing = "S";
var isMoving = false;

var imgSource = "Images/charlieIdle.png";

var w = window.innerWidth;
var h = window.innerHeight;

var charSpeed = 5;
var charX = 50;
var charY = 50;

var ctx;
function onKeyDown(event) {
  var keyPressed = String.fromCharCode(event.keyCode);
  console.log(keyPressed);
  if (keyPressed == "W") {
    isMoving = true;
    facing = "N";
  } else if (keyPressed == "A") {
    isMoving = true;
    facing = "W";
  } else if (keyPressed == "S") {
    isMoving  = true;
    facing = "S";
  } else if (keyPressed == "D") {
    isMoving = true;
    facing = "E;"
  }
}
function onKeyUp(event) {
  var keyPressed = String.fromCharCode(event.keyCode);
  if ((keyPressed == "W")||(keyPressed == "A")||(keyPressed == "S")||(keyPressed == "D")) {
    isMoving = false;
  }
}
function init() {
  var canv = document.getElementById("myCanv");
  ctx = canv.getContext("2d");
  canv.width = w;
  canv.height = h;
  window.addEventListener("keydown", onKeyDown, false);
  window.addEventListener("keyup", onKeyDown, false);
  return setInterval(draw,10);
}
function char() {
  var img = new Image();
  img.onload = function() {
  ctx.drawImage(img,charX,charY);
  };
  img.src = imgSource;
}
function clear() {
  ctx.clearRect(0,0,w,h);
}
function unloadScrollBars() {
    document.documentElement.style.overflow = 'hidden';
}
function moveChar() {
  if (isMoving) {
    if (facing == "N") {charY -= charSpeed;}
    else if (facing == "W") {charX -= charSpeed;}
    else if (facing == "S") {charY += charSpeed;}
    else if (facing == "E") {charX += charSPeed;}
  }
}

function draw() {
  clear();
  char();
  onKeyDown();
  onKeyUp();
  moveChar();
}
init();
unloadScrollBars();
<!DOCTYPE html>
<html>
  <body>
    <canvas id="myCanv" width="500" height="500" style="border:1px solid #888888"> </canvas>
    <script src= "library.js"></script>
    <script src= "game.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

第一次努力!让我想起我什么时候开始编码:)

你最大的问题是你已经使用window.addEventListener连接你的事件处理程序,但是你在draw()函数中再次手动调用它们。 window.addEventListener意味着当按下或释放某个键时,将自动调用onKeyDown函数,以便您可以从draw()函数中删除它们。

function draw() {
  clear();
  char();
  //onKeyDown();
  //onKeyUp();
  moveChar();
}

如果我们再看看你如何连接你的按键事件,那么你已经重复了两次onKeyDown。所以将第二个更改为onKeyUp。

window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);

现在您需要习惯使用调试器窗口(Chrome中的F12)。运行代码和调试我在这一行发现了一个小错字......

facing = "E;"

另一个在这里...

else if (facing == "E") {charX += charSPeed;}

我还必须更改你的图像(因为我没有你的图像)所以检查那部分是否正常工作,我设置以下CSS使画布全屏(没有周围的空白区域)

html,body { margin:0; padding:0; }