SVG.js. Problem with multiple keys pressed simultaneously in pong game

SVG.js. Problem with multiple keys pressed simultaneously in pong game
0

#1

Hello fellow coders.

I have a problem with my 2-player pong game. up-down and w-s respectively control the two paddles. But once a second key is pressed it cancels the former. In this way two keys cannot be pressed at the same time, thus making only one paddle moveable and the other one stuck.

I reckon this to be a valid solution: http://jsfiddle.net/HwR9N/3/, but I’m having trouble understanding it and applying it to my code.

Link to pen: https://codepen.io/sellew/pen/Qgzmbb?editors=0010

The is my event listener:

// Define paddle direction and speed

var paddleDirectionRight = 0; // -1 is up, 1 is down, 0 is still
var paddleDirectionLeft = 0; // -1 is up, 1 is down, 0 is still
var paddleSpeed = 5; // pixels per frame

// detect if up and down arrows are pressed to change direction

SVG.on(document, "keydown", function(e) {
  paddleDirectionRight = e.keyCode == 40 ? 1 : e.keyCode == 38 ? -1 : 0;
  paddleDirectionLeft = e.keyCode == 87 ? -1 : e.keyCode == 83 ? 1 : 0;
});

// Direction is reset once the key is not pressed ('keyup')

SVG.on(document, "keyup", function(e) {
  paddleDirectionRight = 0;
  paddleDirectionLeft = 0;
}) 

The movement of the paddles is inside my function update();


#2

Your code resets the paddle direction to 0 if it’s not one of the two keys to control movement for that paddle. You’ll need to check for a current value before resetting. Something like:

if(paddleDirectionRight === 0) {
    paddleDirectionRight = e.keyCode == 40 ? 1 : e.keyCode == 38 ? -1 : 0;
}

#3

Sorry, that doesn’t seem so solve the issue. I need to somehow temporary store the keys pressed in an array and use these as conditionals. But I can’t figure out how to.