前面两章我们已经研究了如何使用Box2d来模拟游戏世界,这一章就把所有的东西拼凑在一起,最终完成我们的游戏。
一、定义物体
典型的物体:
{type:'ground',name:'dirt',x:500,y:440,width:1000,height:20,isStatic:true},
{type:'ground',name:'wood',x:185,y:390,width:30,height:80,isStatic:true},
典型的物体类型:
'glass':{
fullHealth:100,
density:2.4,
friction:0.4,
restitution:0.15,
},
'wood':{
fullHealth:500,
density:0.7,
friction:0.4,
restitution:0.4,
},
二、添加Box2d
参考前两章
三、创建物体
现在Box2d设置完毕,我们将在entities对象内部实现之前声明的entities.create()方法。该方法接受entities对象为参数,创建物体并将其加入到世界中
create:function(entity){
var definition = entities.definitions[entity.name];
if(!definition){
console.log('无定义名字',entity.name);
return;
}
switch(entity.type){
case 'block'://简单的矩形
entity.health = definition.fullHealth;
entity.fullHealth = definition.fullHealth;
entity.shape = 'rectangle';
entity.sprite = loader.loadImage('images/entities/'+entity.name+'.png');
//entity.breakSound = game.breakSound[entity.name];
box2d.createRectangle(entity,definition);
break;
case 'ground'://简单的矩形
entity.shape = 'rectangle';
//不会被画出,所以不必具有图像
box2d.createRectangle(entity,definition);
break;
case 'hero'://简单的圆
case 'villain'://简单的圆、矩形
entity.health = definition.fullHealth;
entity.fullHealth = definition.fullHealth;
entity.sprite = loader.loadImage('images/entities/'+entity.name+'.png');
entity.shape = definition.shape;
entity.bounceSound = game.bounceSound;
if(definition.shape == 'circle'){
entity.radius = definition.radius;
box2d.createCircle(entity,definition);
}else if(definition.shape == 'rectangle'){
entity.width = definition.width;
entity.height = definition.height;
box2d.createRectangle(entity,definition);
}
break;
default:
console.log('没定义类型',entity.type);
break;
}
},
四、向关卡中加入物体
data:[
{
//level 1
foreground:'desert-foreground',
background:'clouds-background',
entities:[
{type:'ground',name:'dirt',x:500,y:440,width:1000,height:20,isStatic:true},
{type:'ground',name:'wood',x:185,y:390,width:30,height:80,isStatic:true},
{type:'block',name:'wood',x:520,y:380,angle:90,width:100,height:25},
{type:'block',name:'glass',x:520,y:280,angle:90,width:100,height:25},
{type:'villain',name:'burger',x:520,y:205,calories:590},
{type:'block',name:'wood',x:620,y:380,angle:90,width:100,height:25},
{type:'block',name:'glass',x:620,y:280,angle:90,width:100,height:25},
{type:'villain',name:'fries',x:620,y:205,calories:420},
{type:'hero',name:'orange',x:80,y:405},
{type:'hero',name:'apple',x:140,y:405},
]
},
五、设置Box2d调试绘图
首先,在html文件中创建另一个canvas元素
<canvas id="debugcanvas" width="1000" height="480" style="border:1px solid;">
</canvas>
我们在对Box2d进行初始化时,设置调制绘图模式
作者:狂流
出处:http://www.cnblogs.com/kuangliu/
欢迎转载,分享快乐! 如果觉得这篇文章对你有用,请抖抖小手,推荐一下!