明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

使用HTML5 Canvas制作一個(gè)容易的打飛機(jī)游戲

[摘要]這篇文章主要介紹了利用HTML5 Canvas制作一個(gè)簡單的打飛機(jī)游戲,作者也給出了相關(guān)的Javascript代碼,需要的朋友可以參考下之前在當(dāng)耐特的DEMO里看到個(gè)打飛機(jī)的游戲,然后就把他的圖片和音頻扒了了下來。。。。自己憑著玩的心情重新寫了一個(gè)。僅供娛樂哈。。。。。。我沒有用框架,所有js都是...
這篇文章主要介紹了利用HTML5 Canvas制作一個(gè)簡單的打飛機(jī)游戲,作者也給出了相關(guān)的Javascript代碼,需要的朋友可以參考下

之前在當(dāng)耐特的DEMO里看到個(gè)打飛機(jī)的游戲,然后就把他的圖片和音頻扒了了下來。。。。自己憑著玩的心情重新寫了一個(gè)。僅供娛樂哈。。。。。。我沒有用框架,所有js都是自己寫的。。。。。。所以就可以來當(dāng)個(gè)簡單的教程,對(duì)那些剛玩canvas的,或許能有些幫助,樓主玩canvas也不是很久,技術(shù)不是很好,請(qǐng)見諒哈。

  閑話不多說,先上DEMO撒:飛機(jī)游戲 樓主寫這個(gè)人純碎娛樂,沒想著寫成多正式的游戲哈。

  步入主題啦:打飛機(jī)游戲文件有index.html入口文件,allSprite.js精靈的邏輯處理文件,loading.js加載處理文件以及data.js(初始化的一些數(shù)據(jù))。

  首先,正常的游戲基本上都需要一個(gè)loading,loading頁面就是用來預(yù)加載數(shù)據(jù)的,包括精靈表圖片,音頻等,因?yàn)檫@是個(gè)小游戲,要加載的就只有一些音頻和圖片。里面的加載代碼主要就下面這些,其他是制作loading動(dòng)畫的,那個(gè)比較簡單,就不貼了,如果有興趣的直接在DEMO里看控制臺(tái)就行了:

XML/HTML Code復(fù)制內(nèi)容到剪貼板

loadImg:function(datas){   
            var _this = this;   
            var dataIndex = 0;   
            li();   
            function li(){   
                if(datas[dataIndex].indexOf("mp3")>=0){   
                    var audio = document.createElement("audio");   
                    document.body.appendChild(audio);   
                    audio.preload = "auto";   
                    audio.src = datas[dataIndex];   
                    audio.oncanplaythrough = function(){   
                        this.oncanplaythrough = null;   
                        dataIndex++;   
                        if(dataIndex===datas.length){   
                            _this.percent = 100;   
                        }else {   
                            _this.percent = parseInt(dataIndex/datas.length*100);   
                            li.call(_this);   
                        }   
                    }   
                }else {   
                    preLoadImg(datas[dataIndex] , function(){   
                        dataIndex++;   
                        if(dataIndex===datas.length){   
                            _this.percent = 100;   
                        } else {   
                            _this.percent = parseInt(dataIndex/datas.length*100);   
                            li.call(_this);   
                        }   
                    })   
                }   
            }   
        },   

//再貼出preLoadImg的方法   
function preLoadImg(src , callback){   
    var img = new Image();   
    img.src = src;   
    if(img.complete){   
        callback.call(img);   
    }else {   
        img.onload = function(){   
            callback.call(img);   
        }   
    }   
}

我先在data.js里面用一個(gè)數(shù)組保存文件的鏈接,然后判斷這些鏈接是圖片還是音頻,如果是圖片就用preLoadImg加載,預(yù)加載圖片的代碼很簡單,就是new一個(gè)圖片對(duì)象,然后把鏈接賦給它,加載完后再回調(diào)。音頻的加載則是通過生成一個(gè)HTML5的audio dom對(duì)象,把鏈接賦給它,audio有一個(gè)事件“canplaythrough”,瀏覽器預(yù)計(jì)能夠在不停下來進(jìn)行緩沖的情況下持續(xù)播放指定的音頻/視頻時(shí),會(huì)發(fā)生 canplaythrough 事件,也就是說當(dāng)canplaythrough被調(diào)用時(shí),音頻就已經(jīng)被加載的差不多了,可以進(jìn)行下一個(gè)音頻的加載了。就這樣當(dāng)把所有東西都加載完后,再進(jìn)行回調(diào),開始游戲。

  游戲開始了,一個(gè)游戲,會(huì)需要很多的對(duì)象,所以我就統(tǒng)一寫成了一個(gè)精靈對(duì)象,不同對(duì)象之間的每一幀的運(yùn)動(dòng)情況直接用behavior來分別編寫就行了。

XML/HTML Code復(fù)制內(nèi)容到剪貼板

W.Sprite = function(name , painter , behaviors , args){   
    if(name !== undefined) this.name = name;   
    if(painter !== undefined) this.painter = painter;   
    this.top = 0;   
    this.left = 0;   
    this.width = 0;   
    this.height = 0;   
    this.velocityX = 3;   
    this.velocityY = 2;   
    this.visible = true;   
    this.animating = false;   
    this.behaviors = behaviors;   
    this.rotateAngle = 0;   
    this.blood = 50;   
    this.fullBlood = 50;   
    if(name==="plan"){   
        this.rotateSpeed = 0.05;   
        this.rotateLeft = false;   
        this.rotateRight = false;   
        this.fire = false;   
        this.firePerFrame = 10;   
        this.fireLevel = 1;   
    }else if(name==="star"){   
        this.width = Math.random()*2;   
        this.speed = 1*this.width/2;   
        this.lightLength = 5;   
        this.cacheCanvas = document.createElement("canvas");   
        thisthis.cacheCtx = this.cacheCanvas.getContext('2d');   
        thisthis.cacheCanvas.width = this.width+this.lightLength*2;   
        thisthis.cacheCanvas.height = this.width+this.lightLength*2;   
        this.painter.cache(this);   
    }else if(name==="badPlan"){   
        this.badKind = 1;   
        this.speed = 2;   
        this.rotateAngle = Math.PI;   
    }else if(name==="missle"){   
        this.width = missleWidth;   
    }else if(name==="boom"){   
        this.width = boomWidth;   
    }else if(name==="food"){   
        this.width = 40;   
        this.speed = 3;   
        this.kind = "LevelUP"
    }   
    this.toLeft = false;   
    this.toTop = false;   
    this.toRight = false;   
    this.toBottom = false;   

    this.outArcRadius = Math.sqrt((this.width/2*this.width/2)*2);   

    if(args){   
        for(var arg in args){   
            this[arg] = args[arg];   
        }   
    }   
}   
Sprite.prototype = {   
    constructor:Sprite,   
    paint:function(){   
        if(this.name==="badPlan"){this.update();}   

        if(this.painter !== undefined && this.visible){   
            if(this.name!=="badPlan") {   
                this.update();   
            }   
            if(this.name==="plan"  this.name==="missle"  this.name==="badPlan"){   
                ctx.save();   
                ctx.translate(this.left , this.top);   
                ctx.rotate(this.rotateAngle);   
                this.painter.paint(this);   
                ctx.restore();   
            }else {   
                this.painter.paint(this);   
            }   
        }   
    },   
    update:function(time){   
        if(this.behaviors){   
            for(var i=0;i<this.behaviors.length;i++){   
                this.behaviors[i].execute(this,time);   
            }   
        }   
    }   
}

寫出精靈類后,就可以通過編寫每個(gè)的painter以及behavior來生成不同的對(duì)象了。接下來就是寫painter了,painter分成兩種,一種是普通的painter,一種就是精靈表painter,因?yàn)橄癖▌?dòng)畫,飛機(jī)開槍動(dòng)畫,都不是一張圖片就能搞定的,所以就需要用到精靈表了:
2015511181456172.png (168×24)

2015511181533636.png (896×64)

而繪制這些就要為他們定制一個(gè)精靈表繪制器,下面這個(gè)是最簡單的精靈表繪制器,針對(duì)游戲的復(fù)雜性可以相對(duì)的修改精靈表寫法,直到合適,不過原理都大同小異,就是小修小改而已:

XML/HTML Code復(fù)制內(nèi)容到剪貼板

var SpriteSheetPainter = function(cells){   
            this.cells = cells    [];   
            this.cellIndex = 0;   
        }   
        SpriteSheetPainter.prototype = {   
            advance:function(){   
                if(this.cellIndex === this.cells.length-1){   
                    this.cellIndex = 0;   
                }   
                else this.cellIndex++;   
            },   
            paint:function(sprite){   
                var cell = this.cells[this.cellIndex];   
                context.drawImage(spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left , sprite.top , cell.w , cell.h);   
            }   
        }

而普通的繪制器就更簡單了,直接寫一個(gè)painter,把要畫的什么東西都寫進(jìn)去就行了。

有了精靈類和精靈表繪制器后,我們就可以把星星,飛機(jī),子彈,爆炸對(duì)象都寫出來了:下面是整個(gè)allSprite.js的代碼:

JavaScript Code復(fù)制內(nèi)容到剪貼板

(function(W){   
    "use strict"
    var planWidth = 24,   
        planHeight = 24,   
        missleWidth = 70,   
        missleHeight = 70,   
        boomWidth = 60;   
    //精靈類
    W.Sprite = function(name , painter , behaviors , args){   
        if(name !== undefined) this.name = name;   
        if(painter !== undefined) this.painter = painter;   
        this.top = 0;   
        this.left = 0;   
        this.width = 0;   
        this.height = 0;   
        this.velocityX = 3;   
        this.velocityY = 2;   
        this.visible = true;   
        this.animating = false;   
        this.behaviors = behaviors;   
        this.rotateAngle = 0;   
        this.blood = 50;   
        this.fullBlood = 50;   
        if(name==="plan"){   
            this.rotateSpeed = 0.05;   
            this.rotateLeft = false;   
            this.rotateRight = false;   
            this.fire = false;   
            this.firePerFrame = 10;   
            this.fireLevel = 1;   
        }else if(name==="star"){   
            this.width = Math.random()*2;   
            this.speed = 1*this.width/2;   
            this.lightLength = 5;   
            this.cacheCanvas = document.createElement("canvas");   
            this.cacheCtx = this.cacheCanvas.getContext('2d');   
            this.cacheCanvas.width = this.width+this.lightLength*2;   
            this.cacheCanvas.height = this.width+this.lightLength*2;   
            this.painter.cache(this);   
        }else if(name==="badPlan"){   
            this.badKind = 1;   
            this.speed = 2;   
            this.rotateAngle = Math.PI;   
        }else if(name==="missle"){   
            this.width = missleWidth;   
        }else if(name==="boom"){   
            this.width = boomWidth;   
        }else if(name==="food"){   
            this.width = 40;   
            this.speed = 3;   
            this.kind = "LevelUP"
        }   
        this.toLeft = false;   
        this.toTop = false;   
        this.toRight = false;   
        this.toBottom = false;   

        this.outArcRadius = Math.sqrt((this.width/2*this.width/2)*2);   

        if(args){   
            for(var arg in args){   
                this[arg] = args[arg];   
            }   
        }   
    }   
    Sprite.prototype = {   
        constructor:Sprite,   
        paint:function(){   
            if(this.name==="badPlan"){this.update();}   

            if(this.painter !== undefined && this.visible){   
                if(this.name!=="badPlan") {   
                    this.update();   
                }   
                if(this.name==="plan"  this.name==="missle"  this.name==="badPlan"){   
                    ctx.save();   
                    ctx.translate(this.left , this.top);   
                    ctx.rotate(this.rotateAngle);   
                    this.painter.paint(this);   
                    ctx.restore();   
                }else {   
                    this.painter.paint(this);   
                }   
            }   
        },   
        update:function(time){   
            if(this.behaviors){   
                for(var i=0;i<this.behaviors.length;i++){   
                    this.behaviors[i].execute(this,time);   
                }   
            }   
        }   
    }   

    // 精靈表繪制器
    W.SpriteSheetPainter = function(cells , isloop , endCallback , spritesheet){   
        this.cells = cells    [];   
        this.cellIndex = 0;   
        this.dateCount = null;   
        this.isloop = isloop;   
        this.endCallback = endCallback;   
        this.spritesheet = spritesheet;   
    }   
    SpriteSheetPainter.prototype = {   
        advance:function(){   
            this.cellIndex = this.isloop?(this.cellIndex===this.cells.length-1?0:this.cellIndex+1):(this.cellIndex+1);   
        },   
        paint:function(sprite){   
            if(this.dateCount===null){   
                this.dateCount = new Date();   
            }else {   
                var newd = new Date();   
                var tc = newd-this.dateCount;   
                if(tc>40){   
                    this.advance();   
                    this.dateCount = newd;   
                }   
            }   
            if(this.cellIndex<this.cells.length    this.isloop){   
                var cell = this.cells[this.cellIndex];   
                ctx.drawImage(this.spritesheet , cell.x , cell.y , cell.w , cell.h , sprite.left-sprite.width/2 , sprite.top-sprite.width/2 , cell.w , cell.h);   
            } else if(this.endCallback){   
                this.endCallback.call(sprite);   
                this.cellIndex = 0;   
            }   
        }   
    }   

    //特制飛機(jī)精靈表繪制器
    W.controllSpriteSheetPainter = function(cells , spritesheet){   
        this.cells = cells    [];   
        this.cellIndex = 0;   
        this.dateCount = null;   
        this.isActive = false;   
        this.derection = true;   
        this.spritesheet = spritesheet;   
    }   
    controllSpriteSheetPainter.prototype = {   
        advance:function(){   
            if(this.isActive){   
                this.cellIndex++;   
                if(this.cellIndex === this.cells.length){   
                    this.cellIndex = 0;   
                    this.isActive = false;   
                }   
            }   
        },   
        paint:function(sprite){   
            if(this.dateCount===null){   
                this.dateCount = new Date();   
            }else {   
                var newd = new Date();   
                var tc = newd-this.dateCount;   
                if(tc>sprite.firePerFrame){   
                    this.advance();   
                    this.dateCount = newd;   
                }   
            }   
            var cell = this.cells[this.cellIndex];   
            ctx.drawImage(this.spritesheet , cell.x , cell.y , cell.w , cell.h , -planWidth/2 , -planHeight/2 , cell.w , cell.h);   
        }   
    }   

    W.planBehavior = [   
        {execute:function(sprite,time){   
            if(sprite.toTop){   
                sprite.top = sprite.top<planHeight/2? sprite.top : sprite.top-sprite.velocityY;   
            }   
            if(sprite.toLeft){   
                sprite.left = sprite.left<planWidth/2? sprite.left : sprite.left-sprite.velocityX;   
            }   
            if(sprite.toRight){   
                sprite.left = sprite.left>canvas.width-planWidth/2? sprite.left : sprite.left+sprite.velocityX;   
            }   
            if(sprite.toBottom){   
                sprite.top = sprite.top>canvas.height-planHeight/2? sprite.top : sprite.top+sprite.velocityY;   
            }   
            if(sprite.rotateLeft){   
                sprite.rotateAngle -= sprite.rotateSpeed;   
            }   
            if(sprite.rotateRight){   
                sprite.rotateAngle += sprite.rotateSpeed;   
            }   
            if(sprite.fire&&!sprite.painter.isActive){   
                sprite.painter.isActive = true;   
                this.shot(sprite);   

            }   
        },   
        shot:function(sprite){   
            this.addMissle(sprite , sprite.rotateAngle);   
            var missleAngle = 0.1   
            for(var i=1;i<sprite.fireLevel;i++){   
                this.addMissle(sprite , sprite.rotateAngle-i*missleAngle);   
                this.addMissle(sprite , sprite.rotateAngle+i*missleAngle);   
            }   

            var audio = document.getElementsByTagName("audio");   
            for(var i=0;i<audio.length;i++){   
                console.log(audio[i].paused)   
                if(audio[i].src.indexOf("shot")>=0&&audio[i].paused){   
                    audio[i].play();   
                    break;   
                }   
            }   
        },   
        addMissle:function(sprite , angle){   
                for(var j=0;j<missles.length;j++){   
                    if(!missles[j].visible){   
                        missles[j].left = sprite.left;   
                        missles[j].top = sprite.top;   
                        missles[j].rotateAngle = angle;   
                        var missleSpeed = 20;   
                        missles[j].velocityX = missleSpeed*Math.sin(-missles[j].rotateAngle);   
                        missles[j].velocityY = missleSpeed*Math.cos(-missles[j].rotateAngle);   
                        missles[j].visible = true;   
                        break;   
                    }   
                }   
            }   
        }   
    ]   

    W.starBehavior = [   
        {execute:function(sprite,time){   
            if(sprite.top > canvas.height){   
                sprite.left = Math.random()*canvas.width;   
                sprite.top = Math.random()*canvas.height - canvas.height;   
            }   
            sprite.top += sprite.speed;   
        }}   
    ]   

    W.starPainter = {   
        paint:function(sprite){   
            ctx.drawImage(sprite.cacheCanvas , sprite.left-sprite.width/2-sprite.lightLength , sprite.top-sprite.width/2-sprite.lightLength)   
        },   

        cache:function(sprite){   
            sprite.cacheCtx.save();   
            var opacity = 0.5,addopa = 1/sprite.lightLength;   
            sprite.cacheCtx.fillStyle = "rgba(255,255,255,0.8)";   
            sprite.cacheCtx.beginPath();   
            sprite.cacheCtx.arc(sprite.width/2+sprite.lightLength , sprite.width/2+sprite.lightLength , sprite.width/2 , 0 , 2*Math.PI);   
            sprite.cacheCtx.fill();   
            for(var i=1;i<=sprite.lightLength;i+=2){   
                opacity-=addopa;   
                sprite.cacheCtx.fillStyle = "rgba(255,255,255,"+opacity+")";   
                sprite.cacheCtx.beginPath();   
                sprite.cacheCtx.arc(sprite.width/2+sprite.lightLength , sprite.width/2+sprite.lightLength , sprite.width/2+i , 0 , 2*Math.PI);   
                sprite.cacheCtx.fill();   
            }   
        }   
    }   

    W.foodBehavior = [   
        {execute:function(sprite,time){   
            sprite.top += sprite.speed;   
            if(sprite.top > canvas.height+sprite.width){   
                sprite.visible = false;   
            }   
        }}   
    ]   

    W.foodPainter = {   
        paint:function(sprite){   
            ctx.fillStyle = "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+",1)"
            ctx.font="15px 微軟雅黑"
            ctx.textAlign = "center";   
            ctx.textBaseline = "middle";   
            ctx.fillText(sprite.kind , sprite.left , sprite.top);   
        }   
    }   



    W.missleBehavior = [{   
        execute:function(sprite,time){   
            sprite.left -= sprite.velocityX;   
            sprite.top -= sprite.velocityY;   
            if(sprite.left<-missleWidth/2  sprite.top<-missleHeight/2  sprite.left>canvas.width+missleWidth/2  sprite.top<-missleHeight/2){   
                sprite.visible = false;   
            }   
        }   
    }];   

    W.misslePainter = {   
        paint:function(sprite){   
            var img = new Image();   
            img.src="../planGame/image/plasma.png"
            ctx.drawImage(img , -missleWidth/2+1 , -missleHeight/2+1 , missleWidth , missleHeight);   
        }   
    }   

    W.badPlanBehavior = [{   
        execute:function(sprite,time){   
            if(sprite.top > canvas.height    !sprite.visible){   
                var random = Math.random();   

                if(point>=200&&point<400){   
                    sprite.fullBlood = 150;   
                    if(random<0.1){   
                        sprite.badKind = 2;   
                        sprite.fullBlood = 250;   
                    }   
                }else if(point>=400&&point<600){   
                    sprite.fullBlood = 250;   
                    if(random<0.2){   
                        sprite.badKind = 2;   
                        sprite.fullBlood = 400;   
                    }   
                    if(random<0.1){   
                        sprite.badKind = 3;   
                        sprite.fullBlood = 600;   
                    }   
                }else if(point>=600){   
                    sprite.fullBlood = 500;   
                    if(random<0.4){   
                        sprite.badKind = 2;   
                        sprite.fullBlood = 700;   
                    }   
                    if(random<0.2){   
                        sprite.badKind = 3;   
                        sprite.fullBlood = 1000;   
                    }   
                }   

                sprite.visible = true;   
                sprite.blood = sprite.fullBlood;   
                sprite.left = Math.random()*(canvas.width-2*planWidth)+planWidth;   
                sprite.top = Math.random()*canvas.height - canvas.height;   
            }   
            sprite.top += sprite.speed;   
        },   
        shot:function(sprite){   
            this.addMissle(sprite , sprite.rotateAngle);   
            var missleAngle = 0.1   
            for(var i=1;i<sprite.fireLevel;i++){   
                this.addMissle(sprite , sprite.rotateAngle-i*missleAngle);   
                this.addMissle(sprite , sprite.rotateAngle+i*missleAngle);   
            }   
        },   
        addMissle:function(sprite , angle){   
            for(var j=0;j<missles.length;j++){   
                if(!missles[j].visible){   
                    missles[j].left = sprite.left;   
                    missles[j].top = sprite.top;   
                    missles[j].rotateAngle = angle;   
                    var missleSpeed = 20;   
                    missles[j].velocityX = missleSpeed*Math.sin(-missles[j].rotateAngle);   
                    missles[j].velocityY = missleSpeed*Math.cos(-missles[j].rotateAngle);   
                    missles[j].visible = true;   
                    break;   
                }   
            }   
        }   
    }];   

    W.badPlanPainter = {   
        paint:function(sprite){   
            var img = new Image();   
            img.src="../planGame/image/ship.png"
            switch(sprite.badKind){   
                case 1:ctx.drawImage(img , 96 , 0 , planWidth , planWidth , -planWidth/2 , -planHeight/2 , planWidth , planWidth);   
                break;   

                case 2:ctx.drawImage(img , 120 , 0 , planWidth , planWidth , -planWidth/2 , -planHeight/2 , planWidth , planWidth);   
                break;   

                case 3:ctx.drawImage(img , 144 , 0 , planWidth , planWidth , -planWidth/2 , -planHeight/2 , planWidth , planWidth);   
                break;   
            }   

            ctx.strokeStyle = "#FFF";   
            ctx.fillStyle = "#F00";   
            var bloodHeight = 1;   
            ctx.strokeRect(-planWidth/2-1 , planHeight+bloodHeight+3 , planWidth+2 , bloodHeight+2);   
            ctx.fillRect(planWidth/2-planWidth*sprite.blood/sprite.fullBlood , planHeight+bloodHeight+3 , planWidth*sprite.blood/sprite.fullBlood , bloodHeight);   
        }   
    }   

    W.planSize = function(){   
        return {   
            w:planWidth,   
            h:planHeight   
        }       
    }   
})(window);

這些繪制方法之類的都相對(duì)比較簡單。

  主要說一下飛機(jī)的運(yùn)動(dòng)以及對(duì)象數(shù)量的控制,飛機(jī)怎么運(yùn)動(dòng)?毫無疑問,通過鍵盤控制它運(yùn)動(dòng),可能很多人就會(huì)想到通過keydown這個(gè)方法按下的時(shí)候通過判斷keyCode來讓飛機(jī)持續(xù)運(yùn)動(dòng)。但是有個(gè)問題,keydown事件不支持多鍵按下,也就是說,當(dāng)你按下X鍵時(shí),keyCode是88,與此同時(shí)你按下方向鍵后,keyCode會(huì)瞬間變成37,也就是說,如果你單純的想靠keydown來控制飛機(jī)運(yùn)動(dòng),飛機(jī)就只能做一件事,要么只可以往某個(gè)方向移動(dòng),要么只會(huì)開槍。

  所以,我們要通過keydown和keyup來實(shí)現(xiàn)飛機(jī)的運(yùn)動(dòng),原理很容易理解:當(dāng)我們按下往左的方向鍵時(shí),我們給飛機(jī)一個(gè)往左的狀態(tài),也就是讓飛機(jī)的toLeft屬性為true,而在動(dòng)畫循環(huán)中,判斷飛機(jī)的狀態(tài),如果toLeft為true則飛機(jī)的x值不停地減少,飛機(jī)也就會(huì)不停地往左移動(dòng),然后當(dāng)我們抬起手指時(shí)觸發(fā)keyup事件,我們就再keyup事件中解除飛機(jī)往左的狀態(tài)。飛機(jī)也就停止往左移動(dòng)了。其他狀態(tài)也一樣的原理,這樣寫的話,就能夠讓飛機(jī)多種狀態(tài)于一生了。可以同時(shí)開槍同時(shí)到處跑了。

實(shí)現(xiàn)的代碼如下:

XML/HTML Code復(fù)制內(nèi)容到剪貼板

//keydown/keyup事件的綁定     
  window.onkeydown = function(event){   
            switch(event.keyCode){   
                case 88:myplan.fire = true;   
                break;   
                case 90:myplan.rotateLeft=true;   
                break;   
                case 67:myplan.rotateRight=true;   
                break;   
                case 37:myplan.toLeft = true;   
                break;   
                case 38:myplan.toTop = true;   
                break;   
                case 39:myplan.toRight = true;   
                break;   
                case 40:myplan.toBottom = true;   
                break;   
            }   
        }   

        window.onkeyup = function(event){   
            switch(event.keyCode){   
                case 88:myplan.fire = false;   
                break;   
                case 90:myplan.rotateLeft=false;   
                break;   
                case 67:myplan.rotateRight=false;   
                break;   
                case 37:myplan.toLeft = false;   
                break;   
                case 38:myplan.toTop = false;   
                break;   
                case 39:myplan.toRight = false;   
                break;   
                case 40:myplan.toBottom = false;   
                break;   
            }   
        }       


//飛機(jī)每一幀的狀態(tài)更新處理代碼   
execute:function(sprite,time){   
            if(sprite.toTop){   
                spritesprite.top = sprite.top<planHeight/2? sprite.top : sprite.top-sprite.velocityY;   
            }   
            if(sprite.toLeft){   
                spritesprite.left = sprite.left<planWidth/2? sprite.left : sprite.left-sprite.velocityX;   
            }   
            if(sprite.toRight){   
                spritesprite.left = sprite.left>canvas.width-planWidth/2? sprite.left : sprite.left+sprite.velocityX;   
            }   
            if(sprite.toBottom){   
                spritesprite.top = sprite.top>canvas.height-planHeight/2? sprite.top : sprite.top+sprite.velocityY;   
            }   
            if(sprite.rotateLeft){   
                sprite.rotateAngle -= sprite.rotateSpeed;   
            }   
            if(sprite.rotateRight){   
                sprite.rotateAngle += sprite.rotateSpeed;   
            }   
            if(sprite.fire&&!sprite.painter.isActive){   
                sprite.painter.isActive = true;   
                this.shot(sprite);   

            }

就是如此簡單。

  然后說下對(duì)象控制,打飛機(jī)游戲,會(huì)發(fā)射大量子彈,產(chǎn)生大量對(duì)象,包括爆炸啊,飛機(jī)啊,子彈等,如果不停地進(jìn)行對(duì)象的生成和銷毀,會(huì)讓瀏覽器的負(fù)荷變得很大,運(yùn)行了一段時(shí)間后就會(huì)卡出翔了。所以,我們要用可以循環(huán)利用的對(duì)象來解決這個(gè)問題,不進(jìn)行對(duì)象的銷毀,對(duì)所有對(duì)象進(jìn)行保存,循環(huán)利用。

  我的做法就是,在游戲初始化的時(shí)候,直接生成一定數(shù)量的對(duì)象,存放在數(shù)組里面。當(dāng)我們需要一個(gè)對(duì)象的時(shí)候,就從里面取,當(dāng)用完后,再放回?cái)?shù)組里面。數(shù)組里的所有對(duì)象都有一個(gè)屬性,visible,代表對(duì)象當(dāng)前是否可用。

  舉個(gè)例子,當(dāng)我的飛機(jī)發(fā)射一發(fā)炮彈,我需要一發(fā)炮彈,所以我就到炮彈數(shù)組里遍歷,如果遍歷到的炮彈visible為true,也就說明該對(duì)象正在使用著,不能拿來用,所以繼續(xù)遍歷,直到遍歷到visible為false的炮彈對(duì)象,說明這個(gè)對(duì)象暫時(shí)沒人用。然后就可以拿過來重新設(shè)置屬性,投入使用了。當(dāng)炮彈擊中敵人或者打出畫布外的時(shí)候,把炮彈的visible設(shè)成false,又成了一個(gè)沒人用的炮彈在數(shù)組里存放起來等待下一次調(diào)用。

  所以,我們要預(yù)算算好頁面大概要用到多少個(gè)對(duì)象,然后就預(yù)先準(zhǔn)備好對(duì)象,這樣,在游戲進(jìn)行中,不會(huì)有對(duì)象進(jìn)行生成和銷毀,對(duì)游戲性能方面就有了提升了。

  最后再說下音頻,游戲里面要用到多個(gè)同樣的audio才能保證音效的不間斷性:
復(fù)制代碼

XML/HTML Code復(fù)制內(nèi)容到剪貼板

var audio = document.getElementsByTagName("audio");   
                                            for(var i=0;i<audio.length;i++){   
                                                console.log(audio[i].paused)   
                                                if(audio[i].src.indexOf("boom")>=0&&audio[i].paused){   
                                                    audio[i].play();   
                                                    break;   
                                                }   
                                            }

好吧,基本上就這樣了。技術(shù)或許還不夠好,純碎做個(gè)記錄,如果代碼有不當(dāng)正處,歡迎指出,共同學(xué)習(xí)。

相關(guān)推薦:

HTML5 Video/Audio播放本地文件

以上就是利用HTML5 Canvas制作一個(gè)簡單的打飛機(jī)游戲的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!


網(wǎng)站建設(shè)是一個(gè)廣義的術(shù)語,涵蓋了許多不同的技能和學(xué)科中所使用的生產(chǎn)和維護(hù)的網(wǎng)站。