//在页面加载完毕后启动整个Box2D程序
function init() {
//简化缩写各个对象名称
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2AABB = Box2D.Collision.b2AABB;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
//获取画布对象和上下文环境
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//设置缩放比例
var worldScale = 30;
//创建物理世界,设定纵横重力加速度
var world = new b2World(new b2Vec2(0, 10),true);
//获取画布的起始坐标
var canvasPosition=new Object();
canvasPosition.x=8;
canvasPosition.y=8;
//调试绘制并持续刷新
debugDraw();
window.setInterval(update,1000/30);
//绘制四面墙壁
createBox(640,30,320,480,b2Body.b2_staticBody,null);
createBox(640,30,320,0,b2Body.b2_staticBody,null);
createBox(30,480,0,240,b2Body.b2_staticBody,null);
createBox(30,480,640,240,b2Body.b2_staticBody,null);
//先行绘制几个物体
createBox(64,64,100,400,b2Body.b2_staticBody,document.getElementById("house"));
createBox(64,64,300,100,b2Body.b2_dynamicBody,document.getElementById("house"));
//监听鼠标事件
document.addEventListener("mousedown",function(e){
createBox(64,64,e.clientX-canvasPosition.x,e.clientY-canvasPosition.y,b2Body.b2_dynamicBody,document.getElementById("villa"));
});
//绘制物体
function createBox(width,height,pX,pY,type,data){
var bodyDef = new b2BodyDef;
bodyDef.type = type;
bodyDef.position.Set(pX/worldScale,pY/worldScale);
//这个userData就是用来存放图片对象或其它用户数据的
bodyDef.userData=data;
//设置物体多边形形状,此处为矩形
var polygonShape = new b2PolygonShape;
polygonShape.SetAsBox(width/2/worldScale,height/2/worldScale);
//设置物体的各种物理属性
var fixtureDef = new b2FixtureDef;
fixtureDef.density = 1.0;
fixtureDef.friction = 0.5;
fixtureDef.restitution = 0.5;
fixtureDef.shape = polygonShape;
//依据物体的形状和属性在世界中创建出来
var body=world.CreateBody(bodyDef);
body.CreateFixture(fixtureDef);
}
//绘制调试场景和辅助线框
function debugDraw(){
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(30.0);
debugDraw.SetFillAlpha(0);
debugDraw.SetLineThickness(1);
//此处命令可以控制debugDraw显示各种辅助线标示
//debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit | b2DebugDraw.e_aabbBit | b2DebugDraw.e_pairBit | b2DebugDraw.e_centerOfMassBit);
world.SetDebugDraw(debugDraw);
}
//实时刷新显示
function update() {
world.Step(1/30,10,10);
world.DrawDebugData();
//context.drawImage(document.getElementById("sceneback"),0,0);
//绘制渲染到canvas上的过程,其实就是读取世界种所有物体的坐标和角度数据,然后以此绘制物体图片
//world.m_bodyList存储了世界中各个物体的数据
for(var b = world.m_bodyList; b != null; b = b.m_next){
if(b.GetUserData()){
context.save();
context.translate(b.GetPosition().x*worldScale,b.GetPosition().y*worldScale);
context.rotate(b.GetAngle());
context.drawImage(b.GetUserData(),-b.GetUserData().width/2,-b.GetUserData().height/2);
context.restore();
}
}
world.ClearForces();
};
};