乒乓球拍无法正确移动

时间:2019-08-29 18:42:20

标签: javascript user-input pong

我正在使Pong变得更好用JavaScript,但是按下左键时播放器拨片不会移动,而且如果我按下右键也不会停止向右移动。

我已经检查了大小写,分号,并重新排列了代码,但没有任何改变。

var rightPressed = false;
var leftPressed = false;
var paused = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
  if(e.keyCode == 39) {
    rightPressed = true;
  }
  else if(e.keycode == 37) {
    leftPressed = true;
  }
  else if(e.keycode == 32) {
    paused = !paused;
  }//pauses or unpause game
}

//handles when a key isn't being pushed
function keyUpHandler(e) {
  if(e.keycode == 39) {
    rightPressed = false;
  }//tells our code that right isnt being pressed
  else if(e.keyCode == 37) {
    leftPressed = false;
  }//tells code left isnt being pressed
}

var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var paddleY = canvas.height-paddleHeight-10;

function drawPaddle() {
  ctx.fillRect(paddleX,paddleY,paddleWidth,paddleHeight);
  ctx.fillStyle = "white";
}
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall();
  drawPaddle();
  if (!paused){//what to do when paused
    if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
      dx = -dx;
    }
    if (y + dy < ballRadius) {
      dy = -dy;
    }
     if (rightPressed && paddleX < canvas.width-paddleWidth) {
      paddleX += 7;
     }
    else if(leftPressed && paddleX > 0) {
      paddleX -= 7;}
    x += dx;
    y += dy;
    //velocity
  }
}

当我按向右箭头键时,拨片应向右移动;当按向左箭头键时,拨片应向左移动;当按空格键时,桨板应暂停。相反,它不会向左走或暂停,也不会停止向右走。

0 个答案:

没有答案