利用HTML5 Canvas制作一个简单的打飞机游戏
之前在当耐特的demo里看到个打飞机的游戏,然后就把他的图片和音频扒了了下来。。。。自己凭着玩的心情重新写了一个。仅供娱乐哈。。。。。。我没有用框架,所有js都是自己写的。。。。。。所以就可以来当个简单的教程,对那些刚玩canvas的,或许能有些帮助,楼主玩canvas也不是很久,技术不是很好,请见谅哈。
闲话不多说,先上demo撒:飞机游戏 楼主写这个人纯碎娱乐,没想着写成多正式的游戏哈。
步入主题啦:打飞机游戏文件有index.html入口文件,allsprite.js精灵的逻辑处理文件,loading.js加载处理文件以及data.js(初始化的一些数据)。
首先,正常的游戏基本上都需要一个loading,loading页面就是用来预加载数据的,包括精灵表图片,音频等,因为这是个小游戏,要加载的就只有一些音频和图片。里面的加载代码主要就下面这些,其他是制作loading动画的,那个比较简单,就不贴了,如果有兴趣的直接在demo里看控制台就行了:
- 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里面用一个数组保存文件的链接,然后判断这些链接是图片还是音频,如果是图片就用preloadimg加载,预加载图片的代码很简单,就是new一个图片对象,然后把链接赋给它,加载完后再回调。音频的加载则是通过生成一个html5的audio dom对象,把链接赋给它,audio有一个事件“canplaythrough”,浏览器预计能够在不停下来进行缓冲的情况下持续播放指定的音频/视频时,会发生 canplaythrough 事件,也就是说当canplaythrough被调用时,音频就已经被加载的差不多了,可以进行下一个音频的加载了。就这样当把所有东西都加载完后,再进行回调,开始游戏。
游戏开始了,一个游戏,会需要很多的对象,所以我就统一写成了一个精灵对象,不同对象之间的每一帧的运动情况直接用behavior来分别编写就行了。
- 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);
- }
- }
- }
- }
写出精灵类后,就可以通过编写每个的painter以及behavior来生成不同的对象了。接下来就是写painter了,painter分成两种,一种是普通的painter,一种就是精灵表painter,因为像爆炸动画,飞机开枪动画,都不是一张图片就能搞定的,所以就需要用到精灵表了:
而绘制这些就要为他们定制一个精灵表绘制器,下面这个是最简单的精灵表绘制器,针对游戏的复杂性可以相对的修改精灵表写法,直到合适,不过原理都大同小异,就是小修小改而已:
- 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);
- }
- }
而普通的绘制器就更简单了,直接写一个painter,把要画的什么东西都写进去就行了。
有了精灵类和精灵表绘制器后,我们就可以把星星,飞机,子弹,爆炸对象都写出来了:下面是整个allsprite.js的代码:
- (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;
- }
- }
- }
- //特制飞机精灵表绘制器
- 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);
这些绘制方法之类的都相对比较简单。
主要说一下飞机的运动以及对象数量的控制,飞机怎么运动?毫无疑问,通过键盘控制它运动,可能很多人就会想到通过keydown这个方法按下的时候通过判断keycode来让飞机持续运动。但是有个问题,keydown事件不支持多键按下,也就是说,当你按下x键时,keycode是88,与此同时你按下方向键后,keycode会瞬间变成37,也就是说,如果你单纯的想靠keydown来控制飞机运动,飞机就只能做一件事,要么只可以往某个方向移动,要么只会开枪。
所以,我们要通过keydown和keyup来实现飞机的运动,原理很容易理解:当我们按下往左的方向键时,我们给飞机一个往左的状态,也就是让飞机的toleft属性为true,而在动画循环中,判断飞机的状态,如果toleft为true则飞机的x值不停地减少,飞机也就会不停地往左移动,然后当我们抬起手指时触发keyup事件,我们就再keyup事件中解除飞机往左的状态。飞机也就停止往左移动了。其他状态也一样的原理,这样写的话,就能够让飞机多种状态于一生了。可以同时开枪同时到处跑了。
实现的代码如下:
- //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;
- }
- }
- //飞机每一帧的状态更新处理代码
- 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);
- }
就是如此简单。
然后说下对象控制,打飞机游戏,会发射大量子弹,产生大量对象,包括爆炸啊,飞机啊,子弹等,如果不停地进行对象的生成和销毁,会让浏览器的负荷变得很大,运行了一段时间后就会卡出翔了。所以,我们要用可以循环利用的对象来解决这个问题,不进行对象的销毁,对所有对象进行保存,循环利用。
我的做法就是,在游戏初始化的时候,直接生成一定数量的对象,存放在数组里面。当我们需要一个对象的时候,就从里面取,当用完后,再放回数组里面。数组里的所有对象都有一个属性,visible,代表对象当前是否可用。
举个例子,当我的飞机发射一发炮弹,我需要一发炮弹,所以我就到炮弹数组里遍历,如果遍历到的炮弹visible为true,也就说明该对象正在使用着,不能拿来用,所以继续遍历,直到遍历到visible为false的炮弹对象,说明这个对象暂时没人用。然后就可以拿过来重新设置属性,投入使用了。当炮弹击中敌人或者打出画布外的时候,把炮弹的visible设成false,又成了一个没人用的炮弹在数组里存放起来等待下一次调用。
所以,我们要预算算好页面大概要用到多少个对象,然后就预先准备好对象,这样,在游戏进行中,不会有对象进行生成和销毁,对游戏性能方面就有了提升了。
最后再说下音频,游戏里面要用到多个同样的audio才能保证音效的不间断性:
复制代码
- 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;
- }
- }
好吧,基本上就这样了。技术或许还不够好,纯碎做个记录,如果代码有不当正处,欢迎指出,共同学习。
源码地址:https://github.com/whxaxes/canvas-test/tree/gh-pages/src/game-demo/plangame
上一篇: 我国云计算进入理性务实推进新阶段
下一篇: 前端开发浏览器兼容问题