您的位置:首页 > Web前端 > HTML5

Step by Step 使用HTML5开发一个星际大战游戏(1)

2014-12-05 11:33 316 查看

本系列博文翻译自以下文章

http://blog.sklambert.com/html5-canvas-game-panning-a-background/

Languages:HTML5,JavaScript

Code:https://github.com/straker/galaxian-canvas-game/tree/master/part1

1.游戏背景滚动

最终的游戏演示界面如下:

控制:移动–(←↑↓→)箭头
射击–空格

TheHTML5Page

<!DOCTYPEhtml>
<html>
<head>
<title>SpaceShooterDemo</title>
<style>
canvas{
position:absolute;
top:0px;
left:0px;
background:transparent;
}
</style>
</head>
<bodyonload="init()">
<!--Thecanvasforthepanningbackground-->
<canvasid="background"width="600"height="360">
Yourbrowserdoesnotsupportcanvas.Pleasetryagainwithadifferentbrowser.
</canvas>
<scriptsrc="space_shooter_part_one.js"></script>
</body>
</html>


以上代码创建了一个600宽,360高的画布。

基础

创建一个封装全部图像的js对象:

/**
*Defineanobjecttoholdallourimagesforthegamesoimages
*areonlyevercreatedonce.Thistypeofobjectisknownasa
*singleton.
*/
varimageRepository=newfunction(){
//Defineimages
this.background=newImage();
//Setimagessrc
this.background.src="imgs/bg.png";
}




接下来,我们创建
Drawable对象,所有以后的可以运动的物体对象都继承于它,Drawable对象包含一个空的draw方法。


/**
*CreatestheDrawableobjectwhichwillbethebaseclassfor
*alldrawableobjectsinthegame.Setsupdefaultvariables
*thatallchildobjectswillinherit,aswellasthedefault
*functions.
*/
functionDrawable(){
this.init=function(x,y){
//Defaultvariables
this.x=x;
this.y=y;
}
this.speed=0;
this.canvasWidth=0;
this.canvasHeight=0;
//Defineabstractfunctiontobeimplementedinchildobjects
this.draw=function(){
};
}


接下来我们创建背景
Background对象,注意红色部分的代码,红色2句代码是背景移动的核心。


第一句让背景从纵坐标0开始向下移动,第二句
让背景从纵坐标(0-画布)高度开始向下移动,这样就产生了背景在不断向下移动的效果。
最后一句蓝色代码是将
Background对象的原形设置为
Drawable对象,继承
Drawable中的变量和方法。


/**
*CreatestheBackgroundobjectwhichwillbecomeachildof
*theDrawableobject.Thebackgroundisdrawnonthe"background"
*canvasandcreatestheillusionofmovingbypanningtheimage.
*/
functionBackground(){
this.speed=1;//Redefinespeedofthebackgroundforpanning
//Implementabstractfunction
this.draw=function(){
//Panbackground
this.y+=this.speed;
this.context.drawImage(imageRepository.background,this.x,this.y);
//Drawanotherimageatthetopedgeofthefirstimage
this.context.drawImage(imageRepository.background,this.x,this.y-this.canvasHeight);
//Iftheimagescrolledoffthescreen,reset
if(this.y>=this.canvasHeight)
this.y=0;
};
}
//SetBackgroundtoinheritpropertiesfromDrawable
Background.prototype=newDrawable();



最后一步

创建Game对象,Game对象获得web页面中定义的画布,初始化背景对象
Background,设置背景对象的
context以及画布宽,画布高属性。


/**
*CreatestheGameobjectwhichwillholdallobjectsanddatafor
*thegame.
*/
functionGame(){
/*
*Getscanvasinformationandcontextandsetsupallgame
*objects.
*Returnstrueifthecanvasissupportedandfalseifit
*isnot.Thisistostoptheanimationscriptfromconstantly
*runningonolderbrowsers.
*/
this.init=function(){
//Getthecanvaselement
this.bgCanvas=document.getElementById('background');
//Testtoseeifcanvasissupported
if(this.bgCanvas.getContext){
this.bgContext=this.bgCanvas.getContext('2d');
//Initializeobjectstocontaintheircontextandcanvas
//information
Background.prototype.context=this.bgContext;
Background.prototype.canvasWidth=this.bgCanvas.width;
Background.prototype.canvasHeight=this.bgCanvas.height;
//Initializethebackgroundobject
this.background=newBackground();
this.background.init(0,0);//Setdrawpointto0,0
returntrue;
}else{
returnfalse;
}
};
//Starttheanimationloop
this.start=function(){
animate();
};
}


以下是动画功能的实现,其中
requestAnimFrame类似一个timer,会不定期的回调animate()函数;animate()函数中调用
game.background.draw();不断的重绘背景图片的位置,以实现背景滚动的动画效果。




/**
*Theanimationloop.CallstherequestAnimationFrameshimto
*optimizethegameloopanddrawsallgameobjects.This
*functionmustbeagobalfunctionandcannotbewithinan
*object.
*/
functionanimate(){
requestAnimFrame(animate);
game.background.draw();
}
/**
*requestAnimshimlayerbyPaulIrish
*FindsthefirstAPIthatworkstooptimizetheanimationloop,
*otherwisedefaultstosetTimeout().
*/
window.requestAnimFrame=(function(){
returnwindow.requestAnimationFrame||
window.webkitRequestAnimationFrame||
window.mozRequestAnimationFrame||
window.oRequestAnimationFrame||
window.msRequestAnimationFrame||
function(/*function*/callback,/*DOMElement*/element){
window.setTimeout(callback,1000/60);
};
})();


最后启动程序:

/**
*InitializetheGameandstartsit.
*/
vargame=newGame();
functioninit(){
if(game.init())
game.start();
}


最后的运行效果如下:


博主其他系列博文推荐:

1.网络采集软件核心技术剖析系列博文索引

2.手把手教你使用FineUI开发一个b/s结构的取送货管理信息系统系列博文索引
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: