如何在Javascript游戏中检测箭头键?

时间:2017-09-08 01:08:53

标签: javascript html

我做了类似游戏的乒乓球,我想用箭头键而不是鼠标来控制球拍。

由于某种原因,游戏没有检测到按键。此外,当我按P时,我尝试添加暂停游戏功能,但我也坚持这一点。

有人可以帮忙吗?

事件监听器的声明:

document.addEventListener('keydown', event => {
        if (event.keyCode === 38) {
            paddle1 += 5;
        } else if (event.keyCode === 40) {
            paddle1 -= 5;
        } else if (event.keycode === 80) {
            PausePressed;
        }
    });
  

这是带有键盘控制的完整乒乓游戏

    
        var canvas;
        var canvasContext;
        var ballX = 50;
        var ballSpeedX = 10;
        var ballY = 50;
        var ballSpeedY = 5;
        var ym = 10; // the movement of y axis
        var keys = new Array();
        
        var player1Score = 0;
        var player2Score = 0;
        const WinningScore = 5;
        
        var showingWinScreen = false;
        
        var paddle1 = 350;
        var paddle2 = 350;
        const paddleHeight = 100;
        const paddleThickness = 10;
    
        
        
        function PausePressed(evt) {
            if(showingWinScreen) {
                player1Score = 0;
                player2Score = 0;
                showingWinScreen = false;
                
            }
        }
        
        
        
        window.onload =function() {
            canvas = document.getElementById('Mycanvas');
            canvasContext = canvas.getContext('2d');
            window.addEventListener('keydown',doKeyDown,true);
            window.addEventListener('keyup',doKeyUp,true);
    
            var framesPerSecond = 60;
            setInterval(function() {
                moveEverything();
                drawEverything();
            }, 1000/framesPerSecond);
    
     }
     function ballReset(){
         if(player1Score >= WinningScore ||
            player2Score >= WinningScore) {
    
             showingWinScreen = true;
         }
         
         ballX = canvas.width/3;
         ballY = canvas.height/3;
         ballSpeedX = -ballSpeedX
     }       
    
    function doKeyDown(evt){   
            keys[evt.keyCode] = true;
            evt.preventDefault();   // Prevents the page to scroll up/down while pressing arrow keys
        }
    
        function doKeyUp(evt) {
            keys[evt.keyCode] = false;
        }       
        
    function move() {
            if (38 in keys && keys[38]){ //up
                paddle1 += ym;
            }
            if (40 in keys && keys[40]){ //down
                paddle1 -= ym;
            }
    }
        
        function computerMovement() {
            var paddle2Center = paddle2 + (paddleHeight/2);
            if(paddle2Center < ballY - 30) {
              paddle2 = paddle2 + 8;
          } else if(paddle2Center > ballY + 30) {
              paddle2 = paddle2 - 8;
          }  
        }
        
        function moveEverything(){
            if(showingWinScreen) {
                return;
            }
            
            
            
            computerMovement();
            
         ballX = ballX + ballSpeedX;
         ballY = ballY + ballSpeedY;
         if(ballX > canvas.width) {
             if(ballY > paddle2 &&
               ballY < paddle2+paddleHeight) {
                 ballSpeedX = -ballSpeedX;
                 
                 var deltaY = ballY
                        -(paddle2+paddleHeight/2);
                 ballSpeedY = deltaY * 0.25;
                 
             } else {
                 player1Score += 1;
                 ballReset();
             }
         }
         if(ballX < 0) {
             if(ballY > paddle1 &&
               ballY < paddle1+paddleHeight) {
                 ballSpeedX = -ballSpeedX;
                 
                 var deltaY = ballY
                        -(paddle1+paddleHeight/2);
                 ballSpeedY = deltaY * 0.25;
                 
             } else {
                 player2Score += 1;
                 ballReset();
             }
         }
         if(ballY > canvas.height) {
             ballSpeedY = -ballSpeedY
         }
         if(ballY < 0) {
             ballSpeedY = -ballSpeedY
         }
     }
    
        
     function drawNet() {
         for(var i=0;i<canvas.height; i+=40) {
             colorRect(canvas.width/2-1,i,2,20,'white');
         }
     }   
        
     function drawEverything() {
         
    colorRect(0,0,canvas.width,canvas.height,'black');
         
                 if(showingWinScreen) {
                     canvasContext.fillStyle = 'white';
                     
                        if(player1Score >= WinningScore) {
                            canvasContext.font = 'italic 60pt Calibri';
                            canvasContext.fillText('Left Player Won!', 475,350);
                        } else if(player2Score >= WinningScore) {
                            canvasContext.font = 'italic 60pt Calibri';
                            canvasContext.fillText('Right Player Won', 475,350);
                        }
                     
                      canvasContext.font = 'italic 80pt Calibri';  
                     canvasContext.fillText('click to continue', 400,600);
                     
                     
                return;
            }
         
            drawNet();
         
    colorRect(0,paddle1,paddleThickness,paddleHeight,'white');
    colorRect(canvas.width-paddleThickness,paddle2,paddleThickness,paddleHeight,'white');
    colorCircle(ballX, ballY, 10, 'white')
         
         canvasContext.fillText(player1Score, 100,100);
         canvasContext.fillText(player2Score, canvas.width-100,100);
         
     
     }
        function colorRect(leftX,topY, width, height, drawColor) {
            canvasContext.fillStyle = drawColor;
            canvasContext.fillRect(leftX,topY, width,height);
        }
        
        function colorCircle(centerX, centerY, radius, drawColor) {
            canvasContext.fillStyle = drawColor;
            canvasContext.beginPath();
            canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2, true);
            canvasContext.fill();
        }
    
        init();
        
    <html>
        <head>
        
        <title>Ping Pong Game</title>
    
        </head>
    <body bgcolor="#FFB630">
    
    <canvas id="Mycanvas" width="1600" height="800"></canvas>
        
   
        
        <div>
        <h1>The Ping Pong Game</h1>
        
            <h2>Use the mouse to control the paddle!</h2>
        </div>
    
        </body>
    
    </html>

  

这是原始游戏鼠标控制

var canvas;
var canvasContext;
var ballX = 50;
var ballSpeedX = 10;
var ballY = 50;
var ballSpeedY = 5;

var player1Score = 0;
var player2Score = 0;
const WinningScore = 5;

var showingWinScreen = false;

var paddle1 = 350;
var paddle2 = 350;
const paddleHeight = 100;
const paddleThickness = 10;

function calculateMousePos(evt) {
  var rect = canvas.getBoundingClientRect();
  var root = document.documentElement;
  var mouseX = evt.clientX - rect.left - root.scrollLeft;
  var mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x: mouseX,
    y: mouseY
  }
}

function handleMouseClick(evt) {
  if (showingWinScreen) {
    player1Score = 0;
    player2Score = 0;
    showingWinScreen = false;

  }
}

window.onload = function() {
  canvas = document.getElementById('Mycanvas');
  canvasContext = canvas.getContext('2d');

  var framesPerSecond = 60;
  setInterval(function() {
    moveEverything();
    drawEverything();
  }, 1000 / framesPerSecond);

  canvas.addEventListener('mousedown', handleMouseClick);

  canvas.addEventListener('mousemove',
    function(evt) {
      var mousePos = calculateMousePos(evt);
      paddle1 = mousePos.y - (paddleHeight / 2);
    });

}

function ballReset() {
  if (player1Score >= WinningScore ||
    player2Score >= WinningScore) {

    showingWinScreen = true;
  }

  ballX = canvas.width / 3;
  ballY = canvas.height / 3;
  ballSpeedX = -ballSpeedX
}

function computerMovement() {
  var paddle2Center = paddle2 + (paddleHeight / 2);
  if (paddle2Center < ballY - 30) {
    paddle2 = paddle2 + 8;
  } else if (paddle2Center > ballY + 30) {
    paddle2 = paddle2 - 8;
  }
}

function moveEverything() {
  if (showingWinScreen) {
    return;
  }
  computerMovement();

  ballX = ballX + ballSpeedX;
  ballY = ballY + ballSpeedY;
  if (ballX > canvas.width) {
    if (ballY > paddle2 &&
      ballY < paddle2 + paddleHeight) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY -
        (paddle2 + paddleHeight / 2);
      ballSpeedY = deltaY * 0.25;
    } else {
      player1Score += 1;
      ballReset();
    }
  }
  if (ballX < 0) {
    if (ballY > paddle1 &&
      ballY < paddle1 + paddleHeight) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY -
        (paddle1 + paddleHeight / 2);
      ballSpeedY = deltaY * 0.25;
    } else {
      player2Score += 1;
      ballReset();
    }
  }
  if (ballY > canvas.height) {
    ballSpeedY = -ballSpeedY
  }
  if (ballY < 0) {
    ballSpeedY = -ballSpeedY
  }
}

function drawNet() {
  for (var i = 0; i < canvas.height; i += 40) {
    colorRect(canvas.width / 2 - 1, i, 2, 20, 'white');
  }
}



function drawEverything() {

  colorRect(0, 0, canvas.width, canvas.height, 'black');

  if (showingWinScreen) {
    canvasContext.fillStyle = 'white';

    if (player1Score >= WinningScore) {
      canvasContext.font = 'italic 60pt Calibri';
      canvasContext.fillText('Left Player Won!', 475, 350);
    } else if (player2Score >= WinningScore) {
      canvasContext.font = 'italic 60pt Calibri';
      canvasContext.fillText('Right Player Won', 475, 350);
    }

    canvasContext.font = 'italic 80pt Calibri';
    canvasContext.fillText('click to continue!', 400, 600);


    return;
  }

  drawNet();

  colorRect(0, paddle1, paddleThickness, paddleHeight, 'white');
  colorRect(canvas.width - paddleThickness, paddle2, paddleThickness, paddleHeight, 'white');
  colorCircle(ballX, ballY, 10, 'white')

  canvasContext.fillText(player1Score, 200, 100);
  canvasContext.fillText(player2Score, canvas.width - 200, 100);


}

function colorRect(leftX, topY, width, height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX, topY, width, height);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
  canvasContext.fill();
}
<html>

<head>

  <title>Ping Pong Game</title>

</head>

<body>

  <canvas id="Mycanvas" width="1600" height="800"></canvas>


  <div>
    <h1>The Ping Pong Game</h1>

    <h2>Use the mouse to control the paddle!</h2>

  </div>
  <style>
    body {
      background-color: #FFD700;
    }
  </style>

</body>

</html>

2 个答案:

答案 0 :(得分:2)

因此,最大的问题是您从未调用过move()函数。我在move()事件中添加了对keydown函数的调用,然后不断控制记录所发生的所有事情,直到我弄清楚出了什么问题。

这是我编辑过的代码(我离开了console.logs,向您展示我是如何调试它的)。它显示了桨叶在正确的方向上移动。

按住某个键时,您可能还会遇到延迟拨片移动的问题,因为需要一秒时间才能注册按键而不是按下按键。我附上了JS eventhandler引用,以帮助您找到解决方法。

您还需要点击该页面以使其成为焦点。

var canvas;
var canvasContext;
var ballX = 50;
var ballSpeedX = 10;
var ballY = 50;
var ballSpeedY = 5;
var ym = 10; // the movement of y axis
var keys = new Array();

var player1Score = 0;
var player2Score = 0;
const WinningScore = 11115;

var showingWinScreen = false;

var paddle1 = 350;
var paddle2 = 350;
const paddleHeight = 100;
const paddleThickness = 10;



function PausePressed(evt) {
  if (showingWinScreen) {
    player1Score = 0;
    player2Score = 0;
    showingWinScreen = false;

  }
}



window.onload = function() {
  canvas = document.getElementById('Mycanvas');
  canvasContext = canvas.getContext('2d');
  window.addEventListener('keydown', doKeyDown, true);
  window.addEventListener('keyup', doKeyUp, true);

  var framesPerSecond = 60;
  setInterval(function() {
    moveEverything();
    drawEverything();
  }, 1000 / framesPerSecond);

}

function ballReset() {
  if (player1Score >= WinningScore ||
    player2Score >= WinningScore) {

    showingWinScreen = true;
  }

  ballX = canvas.width / 3;
  ballY = canvas.height / 3;
  ballSpeedX = -ballSpeedX
}

function doKeyDown(evt) {
  
  keys[evt.keyCode] = true;
  console.log("current keyCode:",evt.keyCode)
  move()
  evt.preventDefault(); // Prevents the page to scroll up/down while pressing arrow keys
}

function doKeyUp(evt) {
  console.log("'key up' event fired")
  console.log(`keyCode: ${evt.keyCode} keys: ${keys}`)
  console.log(" 'key[evt.keyCode]' before:", keys[evt.keyCode])
  keys[evt.keyCode] = false;
  console.log(" 'key[evt.keyCode]' after:", keys[evt.keyCode])
   console.log(`keyCode: ${evt.keyCode} keys: ${keys}`)
}

function move() {
  console.log("Entered move function")
  if (38 in keys && keys[38]) { //up
    console.log("entered '38 in keys'. UP ")
    console.log("paddle1 before -= :", paddle1)
    paddle1 -= ym;
    console.log("paddle1 after -= :", paddle1)
  }
  else if (40 in keys && keys[40]) { //down
    console.log("entered '40 in keys'. DOWN ")
    console.log("paddle1 before += :", paddle1)
    paddle1 += ym;
    console.log("paddle1 after += :", paddle1)
  }
}

function computerMovement() {
  var paddle2Center = paddle2 + (paddleHeight / 2);
  if (paddle2Center < ballY - 30) {
    paddle2 = paddle2 + 8;
  } else if (paddle2Center > ballY + 30) {
    paddle2 = paddle2 - 8;
  }
}

function moveEverything() {
  if (showingWinScreen) {
    return;
  }



  computerMovement();

  ballX = ballX + ballSpeedX;
  ballY = ballY + ballSpeedY;
  if (ballX > canvas.width) {
    if (ballY > paddle2 &&
      ballY < paddle2 + paddleHeight) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY -
        (paddle2 + paddleHeight / 2);
      ballSpeedY = deltaY * 0.25;

    } else {
      player1Score += 1;
      ballReset();
    }
  }
  if (ballX < 0) {
    if (ballY > paddle1 &&
      ballY < paddle1 + paddleHeight) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY -
        (paddle1 + paddleHeight / 2);
      ballSpeedY = deltaY * 0.25;

    } else {
      player2Score += 1;
      ballReset();
    }
  }
  if (ballY > canvas.height) {
    ballSpeedY = -ballSpeedY
  }
  if (ballY < 0) {
    ballSpeedY = -ballSpeedY
  }
}


function drawNet() {
  for (var i = 0; i < canvas.height; i += 40) {
    colorRect(canvas.width / 2 - 1, i, 2, 20, 'white');
  }
}

function drawEverything() {

  colorRect(0, 0, canvas.width, canvas.height, 'black');

  if (showingWinScreen) {
    canvasContext.fillStyle = 'white';

    if (player1Score >= WinningScore) {
      canvasContext.font = 'italic 60pt Calibri';
      canvasContext.fillText('Left Player Won!', 475, 350);
    } else if (player2Score >= WinningScore) {
      canvasContext.font = 'italic 60pt Calibri';
      canvasContext.fillText('Right Player Won', 475, 350);
    }

    canvasContext.font = 'italic 80pt Calibri';
    canvasContext.fillText('click to continue', 400, 600);


    return;
  }

  drawNet();

  colorRect(0, paddle1, paddleThickness, paddleHeight, 'white');
  colorRect(canvas.width - paddleThickness, paddle2, paddleThickness, paddleHeight, 'white');
  colorCircle(ballX, ballY, 10, 'white')

  canvasContext.fillText(player1Score, 100, 100);
  canvasContext.fillText(player2Score, canvas.width - 100, 100);


}

function colorRect(leftX, topY, width, height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX, topY, width, height);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
  canvasContext.fill();
}
<html>

<head>

  <title>Ping Pong Game</title>

</head>

<body bgcolor="#FFB630">

  <canvas id="Mycanvas" width="1600" height="800"></canvas>



  <div>
    <h1>The Ping Pong Game</h1>

    <h2>Use the mouse to control the paddle!</h2>
  </div>

</body>

</html>

答案 1 :(得分:1)

您需要使用paddle1+=运算符将新值分配给-=

paddle1 += 5相当于paddle1 = paddle1 + 5

paddle1 -= 5相当于paddle1 = paddle1 - 5

你为'p'keydown事件错误拼写keyCode

document.addEventListener('keydown', event => {
    if (event.keyCode === 38) {
        paddle1 += 5;
    } else if (event.keyCode === 40) {
        paddle1 -= 5;
    } else if (event.keyCode === 80) {
        alert('You have pressed p!');
    }
});

进一步阅读加法/减法作业: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment