html – javascript moving a div left and right


So i made this mini game, and I want that my “player” named div to move to left and right inside of the “game” div. but I’m stuck, can someone help me? I think my error is inside of the javascript file… Also if my “player” div moves, will my “gun” div move with it too?

my HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <p>Galaxy Invaders</p>
    <div class="game">
        <div id="player">
            <div id="gun">
                <div id="bullet"></div>
            </div>
        </div>
        <div id="enemy"></div>
    </div>
    <script src="js.js"></script>
</body>
</html>

my CSS

body{
    margin: 0;
    padding: 0;
    background-color: mediumblue;
    height: 800px;
    overflow: hidden;

}
p{
    font-size: 48pt;
    color: black;
    font-family: fantasy;
    font-weight: bold;
    position: relative;
    left: 300px;
    top: -50px;

}

.game{
    width: 800px;
    height: 500px;
    position: center;
    border: 14px solid darkblue;
    border-radius: 5px;
    margin-left: 300px;
    margin-top: -100px;
    background-color: black;


}

#player{
    height: 20px;
    width: 40px;
    background-color: firebrick;
    border-radius: 2px;
    position: relative;
    top: 470px;
    left: 400px;


}
#gun{
    position: relative;
    height: 40px;
    width: 10px;
    background-color: firebrick;
    top: -20px;
    left: 15px;
    border-radius: 2px;

}

#bullet{
    position: relative;
    background-color: darkorange;
    width: 8px;
    height: 20px;
    top: 0;
    left: 1px;
    animation: shoot 0.7s linear;


}

@keyframes shoot {
    0%{top: 0px;}
    100%{top: -470px;}
}


And finally my javascript file:

let modifier = 50;
let player = document.getElementById('player');

window.addEventListener('keydown', (event) => {
    const { style } = player;
    switch (event.key){
        case 'ArrowRight':style.left = `${parseInt(style.left) - modifier}px`;break;
        case 'ArrowLeft':style.left = `${parseInt(style.left) + modifier}px`;break;
    }


});



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here