javascriptkeycode

Codepen, JavaScript, how to add keyCode up and down to paddle


I saw "JavaScript Canvas Tutorial - Move a sprite/character on screen using the keyboard" but it didn't help me how to add keyCode and movements to my paddle. I hope someone can explain and maybe show how to make the keyCode to move my variable "paddle1Y".

var canvas;
var canvasContext;

var ballX = 300;
var ballY = 200;

var paddle1Y = 150;


const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;


window.onload = function (){
  canvas = document.getElementById("gameCanvas");
  canvasContext = canvas.getContext("2d");
  
  var framesPerSecond = 30;
  setInterval(function() {
    drawEverything();
  }, 1000/framesPerSecond);
}

function moveEverything(){

  if(paddle1Y.keyCode == 38){
    paddle1Y -=5;
  }
  if(paddle1Y.keyCode == 40){
    paddle1Y +=5;
  }
  
  
}

//draws all on the gameCanvas which is black.
function drawEverything(){
  //Next line blanks the screen with black
  colorRect(0,0,canvas.width,canvas.height, "black");
  //next line draw left paddle
  colorRect(0,paddle1Y, PADDLE_THICKNESS,PADDLE_HEIGHT, "white");
  //next line draws ball from the function
colorCircle(ballX,ballY,10, "white");
}
// summerize the ball information
function colorCircle(centerX,centerY, radius, drawColor){
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
  canvasContext.fill();
}
//summerize the canvas info, like; Color and width/height
function colorRect(leftX, topY, width,height, drawColor){
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX, topY, width, height);
}
<canvas id = "gameCanvas" width = "800" height= "600"></canvas>


Solution

  • You need to add event handlers for keyboard events and use the passed event in the handler to access the .keyCode (or .which) prop.

    Here is exactly how you can use this in your code:

    var canvas;
    var canvasContext;
    
    var ballX = 300;
    var ballY = 200;
    
    var paddle1Y = 150;
    
    
    const PADDLE_THICKNESS = 10;
    const PADDLE_HEIGHT = 100;
    
    
    window.onload = function (){
      canvas = document.getElementById("gameCanvas");
      canvasContext = canvas.getContext("2d");
      
      var framesPerSecond = 30;
      setInterval(function() {
        drawEverything();
      }, 1000/framesPerSecond);
    }
    
    //draws all on the gameCanvas wich is black.
    function drawEverything(){
      //Next line blanks the screen with black
      colorRect(0,0,canvas.width,canvas.height, "black");
      //next line draw left paddle
      colorRect(0,paddle1Y, PADDLE_THICKNESS,PADDLE_HEIGHT, "white");
      //next line draws ball from the function
    colorCircle(ballX,ballY,10, "white");
    }
    // summerize the ball information
    function colorCircle(centerX,centerY, radius, drawColor){
      canvasContext.fillStyle = drawColor;
      canvasContext.beginPath();
      canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
      canvasContext.fill();
    }
    //summerize the canvas info, like; Color and width/height
    function colorRect(leftX, topY, width,height, drawColor){
      canvasContext.fillStyle = drawColor;
      canvasContext.fillRect(leftX, topY, width, height);
    }
    
    
    function handleKeyDown ( event ) {
      var keyCode = event.which || event.keyCode;
      
      switch (keyCode){
        case 38:
          paddle1Y -=5;
          break;
          
        case 40:
          paddle1Y +=5;
          break;
          
        default:
          // Avoid preventDefault() when not pressing expected keys
          return;
      }
      
      // Don't scroll window when pressing UP/DOWN
      event.preventDefault();
      
    }
    
    document.addEventListener('keydown', handleKeyDown, true);
    <canvas id = "gameCanvas" width = "800" height= "600"></canvas>

    More generic example using the keydown and keyup to track when the keys are pressed:

    var el = document.getElementById('a');
    
    function handleKeyDown ( event ) {
      var key = event.which || event.keyCode;
      el.innerHTML = `${key} <strong>pressed</strong> <br/> ${el.innerHTML}`;
    }
    
    function handleKeyUp ( event ) {
      var key = event.which || event.keyCode;
      el.innerHTML = `${key} <em>released</em> <br/> ${el.innerHTML}`;
    }
    
    document.addEventListener('keydown', handleKeyDown, true);
    document.addEventListener('keyup', handleKeyUp, true);
    <div id="a">NOTHING happened</div>

    Run that snippet and click on/around NOTHING happening then pressed LEFT, RIGHT, etc. to see the effect.


    The same example as above, but a little more modular ... D.R.Y.

    var el = document.getElementById('a');
    
    function initKeyHandler ( statusText ) {
      return function handleKey ( event ) {
        var key = event.which || event.keyCode;
        el.innerHTML = `${key} ${statusText} <br/> ${el.innerHTML}`;
      }
    }
    
    var handleKeyDown = initKeyHandler(`<strong>pressed</strong>`);
    var handleKeyUp = initKeyHandler(`<em>released</em>`);
    
    document.addEventListener('keydown', handleKeyDown, true);
    document.addEventListener('keyup', handleKeyUp, true);
    <div id="a">
      NOTHING happening
    </div>