简单手写一个Javascript版本的飞机大战,全部利用canvas绘制,

最近比较闲,想试试canvas,就写了个飞机大战学习一下,变量名称起的不是很好,勿见怪,懒得替换
关键注释全部在代码注释中
图片存在了图床中如果失效了,请自己找一个素材替换即可
游戏截图

操作方法

上下左右 操控飞机移动
手势操控手机上直接可以,PC需要将下面两行取消注释

window.addEventListener("mousedown", ren)
window.addEventListener("mousemove", ren)

数字1-9可以修改飞机的speed移动速度;
-号可以减一个速度(最小为0,停止)
+号可以加一个速度(没有上限)

空格 :发射子弹,用于打击敌人

<!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">
    <title>飞机大战Demo</title>
</head>



<body>
    <canvas id="canvas"></canvas>
    <script>
        const log = console.log;
        var canvas = document.querySelector("canvas")//获取元素
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        canvas.style.background = "#fff"
        var ctx = canvas.getContext("2d");
        let img = addimg("https://s4.ax1x.com/2022/02/11/HUGxTf.png")//我方飞机
        let fjimg = addimg("https://s4.ax1x.com/2022/02/11/HUJmkT.png")//敌人飞机
        const zidanimg = addimg("https://s4.ax1x.com/2022/02/11/HUGOOI.png")//子弹
        let img4 = addimg('https://s4.ax1x.com/2022/02/11/HUJG0x.png')//背景
        function addimg(url) {
            let imgv = new Image()
            imgv.src = url
            return imgv
        }
        var fen = 0//得分
        var run = false//是否运行
        var index = 0;//背景偏移高度
        let fj = {//我方飞机出生点
            x: canvas.width / 2,
            y: canvas.height - 200
        }
        //游戏渲染入口
        function render() {
            index += 5
            if (index >= canvas.height) {
                index = 0;
            }
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            drawImg()
            move()
            drawzd()
            otherSide()
            drawFJ()
            renderF()
            if (run) {
                window.requestAnimationFrame(render)
                //用官方推荐的循环方式绘制动画
            }
        }

        const size = 100;//飞机尺寸
        function drawFJ() {//
            ctx.drawImage(fjimg, fj.x - size / 2, fj.y - size / 2, size, size)
        }



        /**在画布上画图形 */
        var py = 0
        function drawImg() {//画背景
            if (py > canvas.height) {
                py = 0
            }
            py += 5
            ctx.drawImage(img4, 0, py, canvas.width, canvas.height)
            ctx.drawImage(img4, 0, py - canvas.height, canvas.width, canvas.height)
        }



        //键盘状态 顺序:左右上下  空格(发射子弹按钮)
        const keyEvent = {
            39: false,
            37: false,
            38: false,
            40: false,
            32: false
        }
        var speed = 5 //飞机初速度
        var lasttime = new Date().getTime()
        function move() {
            //控制子弹和飞机移动坐标位置的
            if (keyEvent[39]) {
                fj.x += speed
            }
            if (keyEvent[37]) {
                fj.x -= speed
            }
            if (keyEvent[38]) {
                fj.y -= speed
            }
            if (keyEvent[40]) {
                fj.y += speed
            }
            if (fj.x <= 50) {
                fj.x = 50
            }
            if (fj.x >= innerWidth - 50) {
                fj.x = innerWidth - 50
            }
            if (fj.y <= 50) {
                fj.y = 50
            }
            if (fj.y >= innerHeight - 50) {
                fj.y = innerHeight - 50
            }

            if (keyEvent[32]) {//添加子弹到子弹数组
                const now1 = new Date().getTime()
                log(lasttime, now1, now1 - lasttime)
                if (lasttime < now1 - 200) {
                    //距离上次发射最小间隔200ms
                    lasttime = now1
                    addzd()
                }
            }

        }
        var sideArrr = []//敌机数组
        function renderF() {//得分渲染
            ctx.fillStyle = "red"
            ctx.font = 'bold 35px Arial'
            ctx.fillText(`得分:${fen}`, 10, 35)
        }

        function addfj() {//添加敌方飞机
            x = Math.trunc(Math.random(10) * canvas.width - 50);
            y = -50
            if (x < 0)
                x = 50
            sideArrr.push({ x: x, y: y })
        }
        //碰撞检测关键方法
        function check(A, B, C, D, E, F, G, H) {
            // 转为对角线坐标
            C += A, D += B, G += E, H += F;

            // 没有相交
            if (C <= E || G <= A || D <= F || H <= B)
                return [0, 0, 0, 0];

            var tmpX, tmpY;

            if (E > A) {
                tmpX = G < C ? [E, G] : [E, C];
            } else {
                tmpX = C < G ? [A, C] : [A, G];
            }

            if (F > B) {
                tmpY = H < D ? [F, H] : [F, D];
            } else {
                tmpY = D < H ? [B, D] : [B, H];
            }

            return [tmpX[0], tmpY[0], tmpX[1], tmpY[1]];
        }
        //检查子弹和敌机有无碰撞
        function collision(x, y, w, h) {
            for (let index = 0; index < zdArr.length; index++) {
                const element = zdArr[index];
                let c = check(x, y, w, h, element.x, element.y, 40, 40)
                if (Math.max(...c) > 0) {
                    zdArr.splice(index, 1)//如果敌机和子弹碰撞删除子弹;返回true
                    return true
                }
            }
        }

        /**渲染敌方机器 */
        function otherSide() {
            let c = sideArrr;
            for (let index = 0; index < c.length; index++) {
                const el = c[index];
                el.y += 4
                if (el.y >= innerHeight) {
                    sideArrr.splice(index, 1)
                    continue
                }
                const fy = fj.y - 40
                const fx = fj.x - 50
                if ((el.y + 50 >= fy && el.y + 50 <= fy + 100) && (el.x + 50 >= fx && el.x <= fx + 100)) {
                    // sideArrr.splice(index, 1)
                    run = false;
                    alert("游戏结束,刷新重开")
                }
                let state = collision(el.x, el.y, 50, 50)
                if (state) {//如果敌机和子弹碰撞,删除敌机
                    sideArrr.splice(index, 1)
                    fen += 1;//得分+1
                    continue
                }
                ctx.drawImage(img, el.x, el.y, 50, 50)
            }
            if (sideArrr.length == 0 || sideArrr[sideArrr.length - 1].y > 100) {
                addfj()//如果距离上个敌机坐标大于100像素,在添加一个随机敌机
            }
        }
        var zdArr = []//子弹数组
        const zsize = 40
        /**渲染子弹 */
        function drawzd() {
            let ac = zdArr
            for (let index = 0; index < ac.length; index++) {
                const element = ac[index];
                if (element.y < -50) {
                    zdArr.splice(index, 1)//子弹高度离开屏幕可视区域,销毁子弹
                    continue;
                }
                zdArr[index].y = zdArr[index].y - 5
                ctx.drawImage(zidanimg, element.x, element.y, zsize, zsize)
            }
        }

        function addzd() {//添加子弹
            let x = fj.x - zsize / 2
            let y = fj.y - zsize - 45;
            zdArr.push({ x: x, y: y })

        }
        //这个是监听键盘或者手势操控后设置飞机的位置的方法
        function ren(e) {
            let x = parseInt(e.offsetX || e.touches[0].clientX)
            let y = parseInt(e.offsetY || e.touches[0].clientY)
            let pos = bian(x, y, 100, 100)
            fj.x = pos.x;
            fj.y = pos.y;
        }
        //检测飞机是否碰到边缘方法
        function bian(x, y, w, h) {
            x = Number(x)
            y = Number(y)
            w = w / 2
            h = h / 2
            if (x <= w) {
                x = w
            }
            if (x >= innerWidth - w) {
                x = innerWidth - w
            }
            if (y <= h) {
                y = h
            }
            if (y >= innerHeight - h) {
                y = innerHeight - h
            }
            return { x: x, y: y }
        }
        window.addEventListener("touchmove", ren)//手势移动事件
        window.addEventListener("touchstart", ren)
        // window.addEventListener("mousedown", ren)//这两行是鼠标移动时间,不监听废弃
        // window.addEventListener("mousemove", ren)
        // var isa = false
        window.addEventListener("keydown", (e) => {
            //键盘监听事件  按下后将某个值设为true;渲染的时候用得到
            if (e.key > 0 && e.key <= 9) {
                speed = e.key * 1//如果值为数字则修改飞机速度
            }
            const code = e.keyCode;

            if (code == 109) {//减号减速
                speed = speed - 1 < 0 ? 0 : speed - 1//最小为0
            }
            if (code == 107) {//加号加速
                speed += 1
            }
            keyEvent[code] = true
        })
        window.addEventListener("keyup", function (e) {
            //键盘抬起事件, 抬起后将某个值设置为false ,渲染时就不计算此key的相关内容
            const code = e.keyCode;
            keyEvent[code] = false
        })

        render(run = true)//运行程序
    </script>
</body>
<style>
    * {
        margin: 0px;
        padding: 0px;
        overflow: hidden;
    }
</style>

</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值