技术小白--动画射击游戏代码

215 阅读1分钟
      <!DOCTYPE html>
          <html lang="en">

         <head>
       <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    body {
        background-color: #ccc;
    }

    #range {

        height: 300px;
        width: 100%;
        position: absolute;
        left: 0;
        top: 0;
        background: url(./space.jpg);
        background-size: cover;
        cursor: crosshair;

    }

    #img1 {
        position: absolute;
        border: none;
        left: 0;
        top: 100px;
        padding: 10px;
    }

    #score {
        color: white;
        padding: 10px;
    }
</style>
   </head>

    <body>
         <div id="range">
           <div id="score"></div>
              <img src="./ufo.png" alt="" id="img1">
</div>


<script>
    var timer = null
    var el = null

    var score = 0
    var shots = 0
    function moveIt() {
        if (parseInt(el.style.left) > (screen.width - 50)) {
            el.style.left = 0

        }


        el.style.left = parseInt(el.style.left) + 6 + 'px';

        el.style.top = 100 + (80 * Math.sin(parseInt(el.style.left) / 50)) + 'px';

        timer = setTimeout(moveIt, 25)


    }
    function scoreUp() {
        score++;

    }
    function scoreboard() {
        document.querySelector("#score").innerHTML = "Shots:" + shots + " Score:" + score;

    }
    window.onload = function () {
        el = document.querySelector('#img1')
        el.onclick = scoreUp;
        document.querySelector('#range').onclick = function (){
            shots++
            scoreboard();

        }
        scoreboard()
        el.style.left = '50px'
        moveIt()
    }
</script>
    </body>

    </html>