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();