Im working on a two player battle style game and having some troubles figuring out how to have two elements moving at the same time. I can move them independently with their respective keys which is "a" and "d" for player1 and then "j" and "L" for player2. If player1 is moving and I press a movement key for player2 it stops player1's movement. How can I fix this?
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/style.css">
<script src="./js/app.js" defer></script>
<title>Battle!</title>
</head>
<body>
<div id="board">
<div class="rocks"></div>
<div id="player2"></div>
<div id="player1"></div>
</div>
</body>
</html>
CSS
#board{
position: relative;
width: 750px;
height: 600px;
margin: 20px auto;
border: 20px solid rgb(0, 0, 0);
background-color: blue;
}
#player1{
position: absolute;
width: 40px;
height: 40px;
background: url("/player1.png");
background-size: contain;
background-repeat: no-repeat;
bottom: 0%;
left: 50%;
transform: translateX(-50%);
border: solid black;
}
#player2{
position: absolute;
width: 40px;
height: 40px;
background: url("/debug.png");
background-size: contain;
background-repeat: no-repeat;
top: 0%;
left: 50%;
transform: translateX(-50%);
border: solid black;
}
JAVASCRIPT
window.addEventListener('keydown', (e)=>{
let left = parseInt(window.getComputedStyle(player1).getPropertyValue("left"));
switch(e.key.toLowerCase()){
case 'a':
player1.style.left = left - 10 + 'px';
if (left <= 25) {
player1.style.left = 23 + 'px'
}
break
case 'd':
player1.style.left = left + 10 + 'px';
if (left >= 720) {
player1.style.left = 730 + 'px'
} break
}
})
window.addEventListener('keydown', (e)=>{
let left = parseInt(window.getComputedStyle(player2).getPropertyValue("left"));
switch(e.key.toLowerCase()){
case 'j':
player2.style.left = left - 10 + 'px';
if (left <= 25) {
player2.style.left = 23 + 'px'
}
break
case 'l':
player2.style.left = left + 10 + 'px';
if (left >= 720) {
player2.style.left = 730 + 'px'
} break
}
})
It could be a simple fix but I'm not sure what I need to add in order to have them moving at the same time independently of each other regardless if a key is pressed from the opposing player.