Nimrod Naim Nimrod Naim - 5 months ago 16
Javascript Question

cant move two canvas rectangles at same time

I asked another question today and i have another one..

but first here is the code:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong</title>
<script type="text/javascript">
var x = 100;
var y = 100;
var xmoveFirst = 720;
var ymoveFirst = 0;
var xmoveSecond = 30 ;
var ymoveSecond = 0;
function canvas() {
var can = document.getElementById('theCanvas');
can.style.backgroundColor = "black";
var ctx = can.getContext('2d');

//first player
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);

//second player
ctx.fillStyle = 'white';
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);

//first player move
function move(event) {
ctx.clearRect(0,0,750,750); //clear rects
if (event.keyCode == 40) {
ymoveFirst+=25;
console.log("first,"+ymoveFirst);
}

else if (event.keyCode == 38) {
ymoveFirst-=25;
console.log("first,"+ymoveFirst);
}

else if (event.keyCode == 83) {
ymoveSecond +=25;
}

else if (event.keyCode==87) {
ymoveSecond -=25;
}
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);

}
var movement = document.addEventListener("keydown", move);


}


</script>
</head>
<body onload="canvas()">
<canvas id="theCanvas" width="750" height="750"></canvas>
</body>
</html>





so each one of the rect is moving perfectly :)
but here is the problem..
I cant move them both togheter..

thanks for helping!!

Answer

The problem is, that the browser can only handle 1 pressed key at a time. To bypass this, you need to following things:

  • An array
  • Two event listeners, one for the keydown and one for the keyup event.

The array will hold the currently pressed keys. In the keydown event listener you need to set the element at the same index as the id of the pressed key to true, and in the keyup eventlistener you need to set the same element to false. Example:

var keys = [];

document.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
});

document.addEventListener("keyup", function(e) {
    keys[e.keyCode] = false;
});

This will make sure, that an element stays true until the key is released. You can check, if a key is currently pressed by checking the element with the same index:

if (keys[87]) {
    // The "W" key is pressed
}
if (keys[83]) {
    // The "S" key is pressed
}
/// ...

Note: You shouldn't use else-ifs when you check for the pressed keys.