How to detect arrow keys in a Javascript game?

MysteriousDude

I made a pong like game and I want to control the paddle with arrow keys instead of the mouse.

For some reason the game is not detecting the keypress. Also, I tried adding a pause game function when I press P, but I am also stuck on this.

Can somebody please help?

The declaration of the event listeners:

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

Here's the full pong game with keyboard controls:

    
        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>

And here's the original game with mouse control

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>

Michael Treat

So, the biggest issue is that you were never calling your move() function. I added a call to the move() function to your keydown event and then continually console logged everything that was happening until I figured out what was wrong.

Here is my edited code ( I left the console.logs in to show you how I debugged it). It shows the paddle moving and in the correct direction.

You may also have an issue with the delayed paddle movement when holding down a key because it takes a second to register that the key is being held down instead of pressed. I've attached a JS eventhandler reference to help you out in finding a way around that.

You also need to click the page to bring it in focus.

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>

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How can I detect macOS command keys in JavaScript

分類Dev

How to select without arrow keys in INTELLIJ

分類Dev

react js how to prevent arrow keys from switching controls

分類Dev

How to remap ctrl+arrow keys to move word to word for mac

分類Dev

How to navigate through java menu items with arrow keys (up/down)?

分類Dev

Tkinter listbox that scrolls with arrow keys

分類Dev

Binding to Arrow Keys in Readline Library

分類Dev

Moving an image on a canvas with arrow keys

分類Dev

How to limit the amount of bullets in a JavaScript Game?

分類Dev

How can I go about creating a scrollable page content using arrow keys?

分類Dev

How do I make div or <li> accessible through Up/down arrow keys

分類Dev

In vim, how do I make the left and right arrow keys change line?

分類Dev

How do I scroll through the autocomplete options in emacs-jedi (besides arrow keys)

分類Dev

how to detect mobile numbers in a string using javascript

分類Dev

Javascript: how to create an object with numeric String keys

分類Dev

Recognize arrow keys in Java Scanner or Console application

分類Dev

Angular2 Navigation using Arrow Keys

分類Dev

Meta + Arrow Keys to move windows between monitors?

分類Dev

Remap arrow keys to win+ijkl on linux

分類Dev

Cygwin Terminal backspace and arrow keys not working

分類Dev

Selecting a whole word with CTRL + SHIFT + arrow keys

分類Dev

Other keys not working when using keydown event for arrow keys in KnockoutJs

分類Dev

How to detect non-visible keys (ENTER, F1, SHIFT) altogether using JS or jQuery?

分類Dev

how to draw an arrow in SceneKit?

分類Dev

How to detect volume up button click event using javascript?

分類Dev

How do I detect, with JavaScript, if an image was pasted or dropped into a contenteditable area?

分類Dev

How can a JavaScript app detect if a Leap Motion device is connected

分類Dev

how to detect event when user has disabled javascript in his browser?

分類Dev

How can I detect and parse from one of these string formats in JavaScript?

Related 関連記事

  1. 1

    How can I detect macOS command keys in JavaScript

  2. 2

    How to select without arrow keys in INTELLIJ

  3. 3

    react js how to prevent arrow keys from switching controls

  4. 4

    How to remap ctrl+arrow keys to move word to word for mac

  5. 5

    How to navigate through java menu items with arrow keys (up/down)?

  6. 6

    Tkinter listbox that scrolls with arrow keys

  7. 7

    Binding to Arrow Keys in Readline Library

  8. 8

    Moving an image on a canvas with arrow keys

  9. 9

    How to limit the amount of bullets in a JavaScript Game?

  10. 10

    How can I go about creating a scrollable page content using arrow keys?

  11. 11

    How do I make div or <li> accessible through Up/down arrow keys

  12. 12

    In vim, how do I make the left and right arrow keys change line?

  13. 13

    How do I scroll through the autocomplete options in emacs-jedi (besides arrow keys)

  14. 14

    how to detect mobile numbers in a string using javascript

  15. 15

    Javascript: how to create an object with numeric String keys

  16. 16

    Recognize arrow keys in Java Scanner or Console application

  17. 17

    Angular2 Navigation using Arrow Keys

  18. 18

    Meta + Arrow Keys to move windows between monitors?

  19. 19

    Remap arrow keys to win+ijkl on linux

  20. 20

    Cygwin Terminal backspace and arrow keys not working

  21. 21

    Selecting a whole word with CTRL + SHIFT + arrow keys

  22. 22

    Other keys not working when using keydown event for arrow keys in KnockoutJs

  23. 23

    How to detect non-visible keys (ENTER, F1, SHIFT) altogether using JS or jQuery?

  24. 24

    how to draw an arrow in SceneKit?

  25. 25

    How to detect volume up button click event using javascript?

  26. 26

    How do I detect, with JavaScript, if an image was pasted or dropped into a contenteditable area?

  27. 27

    How can a JavaScript app detect if a Leap Motion device is connected

  28. 28

    how to detect event when user has disabled javascript in his browser?

  29. 29

    How can I detect and parse from one of these string formats in JavaScript?

ホットタグ

アーカイブ