2021-05-12 15:56

使用原生的Javascript+CSS实现的坦克小游戏

wanmatea

WEB前端

(945)

(0)

收藏

实现效果:

Dingtalk_20210512155404.jpg

CSS样式:

<style type="text/css">
        /*坦克样式*/
        .tank{
            background: url(images/tank.png) no-repeat;
            background-size: cover;
            width: 70px;
            height: 70px;
            position: absolute;
            bottom: 0;
        }
        /*子弹样式*/
        .bullet{
            background: url(images/bullet.png) no-repeat;
            background-size: cover;
            width: 10px;
            height: 27px;
            position: absolute;
            bottom:64px;
        }
    </style>

JavaScript:

<script type="text/javascript">
        //坦克移动速度,初始速度为零
        var xspeed=0;
        function $(id){
            return document.getElementById(id);
        }
        //坦克左移动
        function moveLeft(){
            xspeed=-5;
        }
        //坦克右移动
        function moveRight(){
            xspeed=5;
        }
        //发射子弹
        function shoot(){
            //创建一个子弹并附加到body里面
            var bullet=document.createElement("div");
            bullet.className="bullet";
            var tankLeft=$("tank").offsetLeft;
            bullet.style.left=tankLeft+31+"px";
            document.body.appendChild(bullet);
            //设置定时器不停改变子弹的位置,让子弹向上发射
            setInterval(function(){
                var top=bullet.offsetTop;
                bullet.style.top=top-5+"px";
            },50);
        }
        //初始化键盘事件
        function initKeyDown(){
             document.onkeydown=function(){
                switch(event.keyCode){
                    //按左键,坦克向左移动
                    case 37:
                        moveLeft();
                        break;
                    //按右键,坦克向右移动
                    case 39:
                        moveRight();
                        break;
                    //按空格,发射子弹
                    case 32:
                        shoot();
                        break;
                }
            }
        }
        //初始化坦克
        function initTank(){
            //设置定时器,让坦克不停的移动,到两边以后自动改变方向
            setInterval(function(){
                var left=$("tank").offsetLeft;
                //到达右边的边,速度变成负的,向左移动
                if(left>document.body.offsetWidth-70){
                    xspeed=-5;
                }
                //到达左边的边,速度变成正的,向右移动
                else if(left<0){
                    xspeed=5;
                }
                var speed=left+xspeed;
                $("tank").style.left=speed+"px";
            },50);
        }
        window.onload=function(){
             initTank();
             initKeyDown();
        }
    </script>

Html:

<body>
    <div class="tank" id="tank">
    </div>
</body>


0条评论

点击登录参与评论