Pong Tutorial #2: keyListener

Following on from last time, we will now make our paddle move up and down using the W and S keys.

We’ll add two paddles to the canvas this time as we’ll need an opponent.

// var x = 1;
// var y = 1;

var paddleX = 1;
var paddleY = 1;

var paddle2X = 459;
var paddle2Y = 1;

Next we need a keys array to hold our key codes for the W and S keys. Each key on the keyboard has a numerical representation. You can find these KeyCodes using https://keycode.info. W and S for example, have the KeyCodes 87 and 83 respectively.

var keys = [];

Add the KeyListener() function to the end of your code. This function will detect when a key has been pressed on the keyboard and add it to our keys[] array. When a key is released, it will remove it from the keys array.

function keyListener() {
  window.onkeydown = function(e) {
    
    // Get the KeyCode for pressed key.
    // Some browsers use e.keyCode, some e.which
    var key = e.keyCode ? e.keyCode : e.which;
    
    // Add to our keys[] array
    if (!keys.includes(key)) {keys.push(key);}
  }
  window.onkeyup = function(e) {
    
    // Get the KeyCode for released key.
    var key = e.keyCode ? e.keyCode : e.which;
   
    // Remove key from our keys[] array
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] == key) {keys.splice(i, 1)}
    }
  }
}

Next, add keyListener() to our draw() function to run every frame.

function draw() {
  context.clearRect(0, 0, 480, 320);
  keyListener();

  // ...
}

Now we can move the paddle up and down using w and s by checking whether our keys array which is updated by keyListener() contains 87 or 83 aka w and s.

function draw() {
  // ...
	
  var speed = 7;
  if (keys.includes(87) && paddleY > 0) {paddleY-=speed;}
  if (keys.includes(83) && paddleY+100 < 320) {paddleY+=speed;}
	
  requestAnimationFrame(draw);
}
You should now be able to move the paddle up and down using the W and S keys. Next time we'll add a ball to our game.

JavaScript | HTML | CSS | Result

Leave a comment

Website Powered by WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started