• JavaScript游戏开发(3)(笔记)


    素材可以去一位大佬放在github的源码中直接下,见附录。

    七、支持移动设备的横向卷轴游戏

    使用前面我们所学习的部分,组合成为一个游戏。

    是否玩过《疯狂喷气机》(手游)这类游戏,该部分试着做一个类似与它的简单的横板游戏。

    准备

    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">
        <title>JavaScript 2D Game</title>
        <link rel="stylesheet" href="./stylte.css">
    </head>
    
    <body>
        <canvas id="canvas1"></canvas>
        <img src="./player.png" id="playerImage" alt="playerImage">
        <img src="./backgroundImage.png" id="backgroundImage" alt="backgroundImage">
        <img src="./worm.png" id="enemyImage" alt="enemyImage">
    
        <script src="./script.js"></script>
    
        <script src="./script.js"></script>
    </body>
    
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    css

    body{
        background: black;
    }
    
    #canvas1{
        position: absolute;
        top:50%;
        left: 50%;
        transform: translate(-50%,-50%);
        border: 5px solid white;
    }
    
    #playerImage,#backgroundImage,#enemyImage{
        display: none;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    JavaScript

    window.addEventListener('DOMContentLoaded',function(){
        const canvas = this.document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        canvas.width = 800;
        canvas.height = 720;
        let enemies = [];
    
    
        // 输入处理
        class InputHandler{
           
        }
    
        class Player{
    
    
        }
    
        class Background{
    
        }
    
        class Enemy{
    
        }
    
    
        function handleEnemies(){
    
        }
    
    
        function displayStatusText(){
    
        }
    
    
    
        function animate(){
    
            requestAnimationFrame(animate);
        }
    
        animate();
    
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    7.1 角色的简单移动

    我们通过如下代码控制角色移动

    window.addEventListener('DOMContentLoaded',function(){
        const canvas = this.document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        canvas.width = 800;
        canvas.height = 720;
    	let enemies = [];
    
        // 输入处理
        class InputHandler{
            constructor(){
                this.keys = [];
                // 加入上、下、左、右按键,此处使用 indexof保证键唯一,就无视本次输入
                window.addEventListener('keydown',e=>{
                    if ((e.key === 'ArrowDown' ||
                         e.key === 'ArrowUp' ||
                         e.key === 'ArrowLeft' ||
                         e.key === 'ArrowRight') &&
                        this.keys.indexOf(e.key) === -1) {
                        this.keys.push(e.key)
                    }
                    console.log(e.key,this.keys);
                });
    
                // 移除按键
                window.addEventListener('keyup',e=>{
                    if( e.key === 'ArrowDown' ||
                        e.key === 'ArrowUp' ||
                        e.key === 'ArrowLeft' ||
                        e.key === 'ArrowRight'){
                        this.keys.splice(this.keys.indexOf(e.key), 1)
                    }
                    console.log(e.key,this.keys);
                });
            }
        }
    
        class Player{
            constructor(gameWidth,gameHeight){
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.width = 200;
                this.height = 200;
                this.x = 0;
                this.y = this.gameHeight - this.height;
                this.image  = playerImage;
                this.frameX = 0;
                this.frameY = 0;
                
                // 速度
                // x轴
                this.speedX = 0;
                // y轴
                this.speedY = 0;
    
                // 重量
                this.weight = 1;
            }
            draw(context){
                context.fillStyle = 'white';
                context.fillRect(this.x,this.y,this.width,this.height);
                context.drawImage(this.image,this.frameX*this.width,this.frameY*this.height,this.width,this.height,this.x,this.y,this.width,this.height);
            }
    
            update(input){
                // 检测X轴按键
                if(input.keys.indexOf('ArrowRight') > -1){
                    this.speedX = 5;
                }
                else if(input.keys.indexOf('ArrowLeft') > -1){
                    this.speedX = -5;
                }
                else{
                    this.speedX = 0;
                }
    
                // 检测Y轴按键,且只能从地面上起跳
                if(input.keys.indexOf('ArrowUp') > -1 && this.onGround()){
                    this.speedY = -32;
                }
    
            
                this.x = this.x + this.speedX;
                this.y = this.y + this.speedY;
    
                // 避免出界
                if(this.x < 0){
                    this.x = 0
                }
                else if(this.x > this.gameWidth - this.width){
                    this.x = this.gameWidth - this.width;
                }
    
                
                // 跳跃限制
                if(!this.onGround()){
                    this.speedY += this.weight;
                    this.frameY = 1;
                }
                else{
                    this.speedY = 0;
                    this.frameY = 0;
                }
    
                // 避免陷入地面
                if(this.y > this.gameHeight - this.height){
                    this.y = this.gameHeight - this.height;
                }
            }
            onGround(){
                return this.y >= this.gameHeight - this.height;
            }
        }
    
        class Background{
    
        }
    
        class Enemy{
    
        }
    
    
        function handleEnemies(){
    
        }
    
    
        function displayStatusText(){
    
        }
    
    
        const input = new InputHandler();
        const player = new Player(canvas.width,canvas.height);
    
        function animate(){
            ctx.clearRect(0,0,canvas.width,canvas.height);
            player.draw(ctx);
            player.update(input);
            requestAnimationFrame(animate);
        }
    
        animate();
    
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145

    如下,我们完成了通过箭头移动角色

    在这里插入图片描述

    7.2 背景

    	class Background{
            constructor(gameWidth, gameHeight) {
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.image = backgroundImage;
                this.x = 0;
                this.y = 0;
                this.width = 2400;
                this.height = 720;
                this.speed = 7;
            }
            draw(context) {
                context.drawImage(this.image, this.x, this.y, this.width, this.height);
                context.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
            }
    
            update() {
                this.x -= this.speed
                if (this.x < 0 - this.width){
                    this.x = 0;
                } 
            }
        }
    
    	function animate(){
            ctx.clearRect(0,0,canvas.width,canvas.height);
            background.draw(ctx);
            background.update();
            player.draw(ctx);
            player.update(input);
            requestAnimationFrame(animate);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    7.3 加入敌人与帧数控制

    笔者修改了视频的一些代码,并修改了player中的一些代码

    window.addEventListener('DOMContentLoaded',function(){
        const canvas = this.document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        canvas.width = 800;
        canvas.height = 720;
    
        let enemies = [];
    
        // 输入处理
        class InputHandler{
            constructor(){
                this.keys = [];
                // 加入上、下、左、右按键,此处使用 indexof保证键唯一,就无视本次输入
                window.addEventListener('keydown',e=>{
                    if ((e.key === 'ArrowDown' ||
                         e.key === 'ArrowUp' ||
                         e.key === 'ArrowLeft' ||
                         e.key === 'ArrowRight') &&
                        this.keys.indexOf(e.key) === -1) {
                        this.keys.push(e.key)
                    }
                });
    
                // 移除按键
                window.addEventListener('keyup',e=>{
                    if( e.key === 'ArrowDown' ||
                        e.key === 'ArrowUp' ||
                        e.key === 'ArrowLeft' ||
                        e.key === 'ArrowRight'){
                        this.keys.splice(this.keys.indexOf(e.key), 1)
                    }
                });
            }
        }
    
        class Player{
            constructor(gameWidth,gameHeight){
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.width = 200;
                this.height = 200;
                this.x = 0;
                this.y = this.gameHeight - this.height;
                this.image  = playerImage;
                this.frameX = 0;
                this.frameY = 0;
                this.maxFrame = 8;
                // 速度
                // x轴
                this.speedX = 0;
                // y轴
                this.speedY = 0;
    
                // 重量
                this.weight = 1;
    
                //动画20帧
                this.fps = 20;
                this.frameTimer = 0;
                this.frameInterval = 1000/this.fps;
            }
            draw(context){
                context.drawImage(this.image,this.frameX*this.width,this.frameY*this.height,this.width,this.height,this.x,this.y,this.width,this.height);
            }
    
            update(input,deltaTime){
                // 检测X轴按键
                if(input.keys.indexOf('ArrowRight') > -1){
                    this.speedX = 5;
                }
                else if(input.keys.indexOf('ArrowLeft') > -1){
                    this.speedX = -5;
                }
                else{
                    this.speedX = 0;
                }
    
                // 检测Y轴按键,且只能从地面上起跳
                if(input.keys.indexOf('ArrowUp') > -1 && this.onGround()){
                    this.speedY = -32;
                    this.frameY = 1;
                    this.frameX = 0;
                    this.maxFrame = 5;
                    this.y = this.y + this.speedY;
                }
    
                if(this.frameTimer > this.frameInterval){
                    if(this.frameX >= this.maxFrame){
                        this.frameX = 0;
                    }
                    else{
                        this.frameX++;
                    }
                    this.frameTimer = 0;
                }
                else{
                    this.frameTimer += deltaTime; 
                }
            
                this.x = this.x + this.speedX;
    
                // 避免出界
                if(this.x < 0){
                    this.x = 0
                }
                else if(this.x > this.gameWidth - this.width){
                    this.x = this.gameWidth - this.width;
                }
    
                
                // 跳跃限制
                if(!this.onGround()){
                    this.speedY += this.weight;
                    this.y = this.y + this.speedY;
                    if(this.onGround()){
                        this.y = this.gameHeight - this.height;
                        this.speedY = 0;
                        this.frameY = 0;
                        this.maxFrame = 8;
                    }
                }
    
            }
    
            // 是否在地面
            onGround(){
                return this.y >= this.gameHeight - this.height;
            }
        }
    
        class Background{
            constructor(gameWidth, gameHeight) {
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.image = backgroundImage;
                this.x = 0;
                this.y = 0;
                this.width = 2400;
                this.height = 720;
                this.speed = 7;
            }
            draw(context) {
                context.drawImage(this.image, this.x, this.y, this.width, this.height);
                context.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
            }
    
            update() {
                this.x -= this.speed
                if (this.x < 0 - this.width){
                    this.x = 0;
                } 
            }
        }
    
        class Enemy{
            constructor(gameWidth, gameHeight) {
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.width = 160;
                this.height = 119;
    
    
                this.image = enemyImage;
    
                this.x = this.gameWidth;
                this.y = this.gameHeight - this.height;
    
                this.frameX = 0;
                this.maxFrame = 5;
    
                this.speed = 8;
    
                // 敌人动画20帧
                this.fps = 20;
                this.frameTimer = 0;
                this.frameInterval = 1000/this.fps;
    
                this.markedForDeletion = false;
            }
            draw(context) {
                context.drawImage(this.image, this.frameX * this.width, 0, this.width, this.height, this.x, this.y, this.width, this.height)
            }
            update(deltaTime) {
                if(this.frameTimer > this.frameInterval){
                    if(this.frameX >= this.maxFrame){
                        this.frameX = 0;
                    }
                    else{
                        this.frameX++;
                    }
                    this.frameTimer = 0;
                }
                else{
                    this.frameTimer += deltaTime; 
                }
    
                if(this.x < 0 - this.width){
                    this.markedForDeletion = true;
                }
    
                this.x -= this.speed;
            }
        }
    
    
        function handleEnemies(deltaTime){
            if(enemyTimer > enemyInterval + randomEnemyInterval){
                enemies.push(new Enemy(canvas.width,canvas.height));
                randomEnemyInterval = Math.random()*1000 + 500;
                enemyTimer = 0;
            }
            else{
                enemyTimer += deltaTime;
            }
            let flag = false;
            enemies.forEach(e => {
                e.draw(ctx);
                e.update(deltaTime);
                if(!flag && e.markedForDeletion){
                    flag = true;
                }
            })
            if(flag){
                enemies = enemies.filter(e=>!e.markedForDeletion);
            }
        }
    
    
        function displayStatusText(){
            
        }
    
    
        const input = new InputHandler();
        const player = new Player(canvas.width,canvas.height);
        const background = new Background(canvas.weight,canvas.height);
    
        let lastTime = 0;
        let enemyTimer = 0;
        let enemyInterval = 2000;
        // 让敌人刷出时间不可预测
        let randomEnemyInterval = Math.random()*1000 + 500;
    
        // 60帧,游戏画面的更新帧
        let frameTimer = 0;
        let frameInterval = 1000/60;
    
    
        function animate(timeStamp){
            const deltaTime = timeStamp - lastTime;
            lastTime = timeStamp; 
            frameTimer += deltaTime; 
            if(frameTimer > frameInterval){
                ctx.clearRect(0,0,canvas.width,canvas.height);
    
                background.draw(ctx);
                // background.update();
        
                handleEnemies(deltaTime);
                player.draw(ctx);
                player.update(input,deltaTime);
                frameTimer = 0;
            }
            requestAnimationFrame(animate);
        }
    
        animate(0);
    
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269

    在这里插入图片描述

    7.4 碰撞、计分、重新开始

    我们碰撞盒采用圆形,来做简单的碰撞检测

    window.addEventListener('DOMContentLoaded',function(){
        const canvas = this.document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        canvas.width = 800;
        canvas.height = 720;
    
        let enemies = [];
    
        // 输入处理
        class InputHandler{
            constructor(){
                this.keys = [];
                // 加入上、下、左、右按键,此处使用 indexof保证键唯一,就无视本次输入
                window.addEventListener('keydown',e=>{
                    if ((e.key === 'ArrowDown' ||
                         e.key === 'ArrowUp' ||
                         e.key === 'ArrowLeft' ||
                         e.key === 'ArrowRight') &&
                        this.keys.indexOf(e.key) === -1) {
                        this.keys.push(e.key)
                    }
                    else if(e.key === 'Enter' && gameOver){
                        gameReStart();
                    }
                });
    
                // 移除按键
                window.addEventListener('keyup',e=>{
                    if( e.key === 'ArrowDown' ||
                        e.key === 'ArrowUp' ||
                        e.key === 'ArrowLeft' ||
                        e.key === 'ArrowRight'){
                        this.keys.splice(this.keys.indexOf(e.key), 1)
                    }
                });
            }
        }
    
        class Player{
            constructor(gameWidth,gameHeight){
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.width = 200;
                this.height = 200;
                this.x = 0;
                this.y = this.gameHeight - this.height;
                this.image  = playerImage;
                this.frameX = 0;
                this.frameY = 0;
                this.maxFrame = 8;
                // 速度
                // x轴
                this.speedX = 0;
                // y轴
                this.speedY = 0;
    
                // 重量
                this.weight = 1;
    
                //动画20帧
                this.fps = 20;
                this.frameTimer = 0;
                this.frameInterval = 1000/this.fps;
            }
            draw(context){
                context.strokeStyle = 'white';
                context.strokeRect(this.x,this.y,this.width,this.height);
                context.beginPath();
                context.arc(this.x + this.width/2,this.y+this.height/2,this.width/2,0,Math.PI*2);
                context.stroke();
    
                context.drawImage(this.image,this.frameX*this.width,this.frameY*this.height,this.width,this.height,this.x,this.y,this.width,this.height);
            }
    
            update(input,deltaTime){
                // 碰撞检测
                enemies.forEach(e=>{
                    const dx = (e.x + e.width/2) - (this.x + this.width/2);
                    const dy = (e.y + e.height/2) - (this.y + this.height/2);
                    const distance = Math.sqrt(dx*dx + dy*dy);
                    if(distance < e.width/2 + this.width/2){
                        gameOver = true;
                    }
                });
    
    
                // 检测X轴按键
                if(input.keys.indexOf('ArrowRight') > -1){
                    this.speedX = 5;
                }
                else if(input.keys.indexOf('ArrowLeft') > -1){
                    this.speedX = -5;
                }
                else{
                    this.speedX = 0;
                }
    
                // 检测Y轴按键,且只能从地面上起跳
                if(input.keys.indexOf('ArrowUp') > -1 && this.onGround()){
                    this.speedY = -32;
                    this.frameY = 1;
                    this.frameX = 0;
                    this.maxFrame = 5;
                    this.y = this.y + this.speedY;
                }
    
                if(this.frameTimer > this.frameInterval){
                    if(this.frameX >= this.maxFrame){
                        this.frameX = 0;
                    }
                    else{
                        this.frameX++;
                    }
                    this.frameTimer = 0;
                }
                else{
                    this.frameTimer += deltaTime; 
                }
            
                this.x = this.x + this.speedX;
    
                // 避免出界
                if(this.x < 0){
                    this.x = 0
                }
                else if(this.x > this.gameWidth - this.width){
                    this.x = this.gameWidth - this.width;
                }
    
                
                // 跳跃限制
                if(!this.onGround()){
                    this.speedY += this.weight;
                    this.y = this.y + this.speedY;
                    if(this.onGround()){
                        this.y = this.gameHeight - this.height;
                        this.speedY = 0;
                        this.frameY = 0;
                        this.maxFrame = 8;
                    }
                }
    
            }
    
            // 是否在地面
            onGround(){
                return this.y >= this.gameHeight - this.height;
            }
    
            restart(){
                this.x = 0;
                this.y = this.gameHeight - this.height;
                this.frameInterval = 0;
                this.maxFrame = 8;
                this.frameY = 0;
            }
        }
    
        class Background{
            constructor(gameWidth, gameHeight) {
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.image = backgroundImage;
                this.x = 0;
                this.y = 0;
                this.width = 2400;
                this.height = 720;
                this.speed = 5;
            }
            draw(context) {
                context.drawImage(this.image, this.x, this.y, this.width, this.height);
                context.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
            }
    
            update() {
                this.x -= this.speed
                if (this.x < 0 - this.width){
                    this.x = 0;
                } 
            }
    
            restart(){
                this.x = 0;
            }
        }
    
        class Enemy{
            constructor(gameWidth, gameHeight) {
                this.gameWidth = gameWidth;
                this.gameHeight = gameHeight;
                this.width = 160;
                this.height = 119;
    
    
                this.image = enemyImage;
    
                this.x = this.gameWidth;
                this.y = this.gameHeight - this.height;
    
                this.frameX = 0;
                this.maxFrame = 5;
    
                this.speed = 8;
    
                // 敌人动画20帧
                this.fps = 20;
                this.frameTimer = 0;
                this.frameInterval = 1000/this.fps;
    
                this.markedForDeletion = false;
            }
            draw(context) {
                context.strokeStyle = 'white';
                context.strokeRect(this.x,this.y,this.width,this.height);
                context.beginPath();
                context.arc(this.x + this.width/2,this.y+this.height/2,this.width/2,0,Math.PI*2);
                context.stroke();
                
                context.drawImage(this.image, this.frameX * this.width, 0, this.width, this.height, this.x, this.y, this.width, this.height)
            }
            update(deltaTime) {
                if(this.frameTimer > this.frameInterval){
                    if(this.frameX >= this.maxFrame){
                        this.frameX = 0;
                    }
                    else{
                        this.frameX++;
                    }
                    this.frameTimer = 0;
                }
                else{
                    this.frameTimer += deltaTime; 
                }
    
                if(this.x < 0 - this.width){
                    this.markedForDeletion = true;
                    score++;
                }
    
                this.x -= this.speed;
            }
    
        }
    
    
        function handleEnemies(deltaTime){
            if(enemyTimer > enemyInterval + randomEnemyInterval){
                enemies.push(new Enemy(canvas.width,canvas.height));
                randomEnemyInterval = Math.random()*1000 + 500;
                enemyTimer = 0;
            }
            else{
                enemyTimer += deltaTime;
            }
            let flag = false;
            enemies.forEach(e => {
                e.draw(ctx);
                e.update(deltaTime);
                if(!flag && e.markedForDeletion){
                    flag = true;
                }
            })
            if(flag){
                enemies = enemies.filter(e=>!e.markedForDeletion);
            }
        }
    
    
        const input = new InputHandler();
        const player = new Player(canvas.width,canvas.height);
        const background = new Background(canvas.weight,canvas.height);
    
        let lastTime = 0;
        let enemyTimer = 0;
        let enemyInterval = 2000;
        // 让敌人刷出时间不可预测
        let randomEnemyInterval = Math.random()*1000 + 500;
    
        // 60帧,游戏画面的更新帧
        let frameTimer = 0;
        let frameInterval = 1000/60;
    
        let score = 0;
        let gameOver = false;
    
    
        function displayStatusText(context){
            context.textAlign = 'left';
            context.fillStyle = 'black';
            context.font = '40px Helvetica';
            context.fillText('score:'+score,20,50);
            context.fillStyle = 'white';
            context.font = '40px Helvetica';
            context.fillText('score:'+score,22,52);
            if(gameOver){
                context.textAlign = 'center';
                context.fillStyle = 'black';
                context.fillText('Game Over,press "Enter" to restart!',canvas.width/2,200);
                context.fillStyle = 'white';
                context.fillText('Game Over,press "Enter" to restart!',canvas.width/2,200);
            }
        }
    
    
    
        function animate(timeStamp){
            const deltaTime = timeStamp - lastTime;
            lastTime = timeStamp; 
            frameTimer += deltaTime; 
            if(frameTimer > frameInterval){
                ctx.clearRect(0,0,canvas.width,canvas.height);
    
                background.draw(ctx);
                background.update();
        
                handleEnemies(deltaTime);
                player.draw(ctx);
                player.update(input,deltaTime);
                displayStatusText(ctx);
                frameTimer = 0;
            }
            if(!gameOver){
                requestAnimationFrame(animate);
            }
        }
    
        animate(0);
    
        function gameReStart(){
            player.restart();
            background.restart();
    
            score = 0;
            enemies = [];
            gameOver = false;
    
            frameTimer = 0;
            enemyTimer = 0;
            lastTime = 0;
    
            randomEnemyInterval = Math.random()*1000 + 500;
            animate(0);
        }
    });
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347

    在这里插入图片描述

    7.5 手机格式

    我们进入浏览器的开发者模式,将浏览器设置为手机。

    *{
        margin: 0;
        padding:0;
        box-sizing: border-box;
    }
    body{
        background: black;
    }
    
    #canvas1{
        position: absolute;
        top:50%;
        left: 50%;
        transform: translate(-50%,-50%);
        border: 5px solid white;
        max-width: 100%;
        max-height: 100%;
    }
    
    #playerImage,#backgroundImage,#enemyImage{
        display: none;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述
    输入的指令如下

    
    			this.touchY = ''; // Y 轴滑动
                this.touchThreshold = 30 ;// 超过30认为滑动
                window.addEventListener('keydown', e => {
                    if ((e.key === 'ArrowDown' ||
                            e.key === 'ArrowUp' ||
                            e.key === 'ArrowLeft' ||
                            e.key === 'ArrowRight') &&
                        this.keys.indexOf(e.key) === -1) {
                        this.keys.push(e.key);
                    }else if(e.key==='Enter'&&gameOver) restartGame()
                })
                // 手指、指针起始位置
                window.addEventListener('touchstart',e=>{
                    this.touchY=e.changedTouches[0].pageY;
                })
                // 手指、指针移动中
                window.addEventListener('touchmove',e=>{
                    const swipeDistance=e.changedTouches[0].pageY-this.touchY;
                    if(swipeDistance<-this.touchThreshold && this.keys.indexOf('swipe up')===-1) {
                    	this.keys.push('swipe up');
                    }
                    else if(swipeDistance>this.touchThreshold && this.keys.indexOf('swipe down')===-1) {
                        this.keys.push('swipe down');
                        if(gameOver) restartGame();
                    }
                }) 
                // 手指、指针移动结束
                window.addEventListener('touchend',e=>{
                    console.log(this.keys);
                    this.keys.splice(this.keys.indexOf('swipe up'),1);
                    this.keys.splice(this.keys.indexOf('swipe down'),1);
                }) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    判断时,只需要在执行处加入相应的标志即可。

    同理,我们可以加入横向滑动操作,随着如果手指沿着X轴移动,我们可以认为X轴方向移动角色。X轴位移不为0则加入,为0则停止。

    如果进入手机模式,滑动时,窗口也跟着滑动,可以试着加入如下代码

           function stopScroll() {
            var html = document.getElementsByTagName('html')[0];
            var body = document.getElementsByTagName('body')[0];
            var o = {};
            o.can = function () {
                html.style.overflow = "visible";
                html.style.height = "auto";
                body.style.overflow = "visible";
                body.style.height = "auto";
            },
                o.stop = function () {
                    html.style.overflow = "hidden";
                    html.style.height = "100%";
                    body.style.overflow = "hidden";
                    body.style.height = "100%";
                }
            return o;
        }
        const scroll = stopScroll();
        scroll.stop();  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    7.6 全屏模式

    #fullScreenButton{
        position: absolute;
        font-size: 20px;
        padding: 10px;
        top: 10px;
        left: 50%;
        transform: translateX(-50%);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    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>JavaScript 2D Gametitle>
        <link rel="stylesheet" href="./stylte.css">
    head>
    
    <body>
        <canvas id="canvas1">canvas>
        <img src="./player.png" id="playerImage" alt="playerImage">
        <img src="./backgroundImage.png" id="backgroundImage" alt="backgroundImage">
        <img src="./worm.png" id="enemyImage" alt="enemyImage">
        <button id="fullScreenButton">Toggle Fullscreenbutton>
    
        <script src="./script.js">script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    function toggleFullScreen(){
            if(!document.fullscreenElement){
                canvas.requestFullscreen().then().catch(err=>{
                    alert(`错误,切换全屏模式失败:${err.message}`)
                })
            }else{
                document.exitFullscreen()
            }
        }
        fullScreenButton.addEventListener('click',toggleFullScreen)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    7.7 存在的问题

    1. 碰撞盒太大了,我们可能需要移动和缩小,来让判定更准确,或者玩起来更容易
    2. 没有很好的填充满屏幕,需要相应的js算法来帮助

    其他笔者未解决问题:

    1. 如上方式,在重新开始后,游戏角色动作”变快“(时间间隔仍旧一样)。
    2. 此外,我们重新开始后,必然立即刷一只怪物
    3. 一些浏览器的页面再切换后,我们隔一段时间再返回,可以刷出更多怪物

    考虑如果自己通过循环来计数,是否可以解决部分问题。

    附录

    [1]源-素材地址
    [2]源-视频地址
    [3]搬运视频地址(JavaScript 游戏开发)
    [4]github-视频的素材以及源码

  • 相关阅读:
    一文教你搞定Python如何自定义标准排序
    【C++】-还在玩普通的类吗,这里面有好几种特殊的类的设计,快进来看看
    NeuralODF: Learning Omnidirectional Distance Fields for 3D Shape Representation
    Git Cherry Pick命令
    CCF CSP认证历年题目自练 Day40
    代码随想录 | Day 55 - LeetCode 392. 判断子序列、LeetCode 115. 不同的子序列
    7z命令行
    c语言入门---调试技巧
    P2P去中心化网络的重点组件
    C语言系统化精讲(六):C语言选择结构和循环结构
  • 原文地址:https://blog.csdn.net/weixin_46949627/article/details/127832514