一、命令行创建库项目(第三方库项目与 Egret 项目不能嵌套。请不要在Egret 项目目录下面创建第三方库项目):
egret create_lib Box2dweb
得到项目目录如图:
二、拖入第三方库文件(点击下载):
- 把Box2dweb.d.ts和Box2dweb.js文件拖到src目录下;
- 把egret.d.ts文件(如图所示文件)拖到libs目录下;
三、修改package.json文件:
在这一行添加Box2dweb.d.ts和Box2dweb.js文件名即可,其它不用动。
四、配置使用box2dweb:
先命令行build一下库项目:egret build Box2dweb
修改项目文件egretProperties.json添加:
说明:path是库项目的路径,我这里是放在工程项目的上一个文件夹下。不理解的话你也可以写全路径名:D:\Egret\workspace\Box2dweb
最后编译一下引擎即可使用!
五、测试(复制可用):
class Box2dTest extends egret.DisplayObjectContainer {
public constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
private world:Box2D.Dynamics.b2World;
private debug:Box2D.Dynamics.b2DebugDraw;
private p2m:number = 30;
private onAddToStage(event:egret.Event) {
var sWidth:number = this.stage.stageWidth;
var sHeight:number = this.stage.stageHeight;
this.createWorld();
this.createDebug();
for(var i:number = 0;i<20;i++){
this.createBox(Math.random()*300+50,Math.random()*200+50,Math.random()*30+10,Math.random()*30+10);
}
this.createBox(sWidth/2,sHeight,sWidth,10,true);
this.createBox(sWidth/2,0,sWidth,10,true);
this.createBox(0,sHeight/2,10,sHeight,true);
this.createBox(sWidth,sHeight/2,10,sHeight,true);
this.addEventListener(egret.Event.ENTER_FRAME,this.loop,this);
}
private createBox(posX:number,posY:number,w:number,h:number,isStatic:boolean=false){
var bodyDef:Box2D.Dynamics.b2BodyDef = new Box2D.Dynamics.b2BodyDef();
bodyDef.position = new Box2D.Common.Math.b2Vec2(posX/this.p2m,posY/this.p2m);
bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
if(isStatic) {
bodyDef.type = Box2D.Dynamics.b2Body.b2_staticBody;
}
var body:Box2D.Dynamics.b2Body = this.world.CreateBody(bodyDef);
var poly:Box2D.Collision.Shapes.b2PolygonShape;
poly = Box2D.Collision.Shapes.b2PolygonShape.AsBox(w/this.p2m,h/this.p2m);
var fixtureDef:Box2D.Dynamics.b2FixtureDef = new Box2D.Dynamics.b2FixtureDef();
fixtureDef.density = 3;
fixtureDef.restitution = 0.2;
fixtureDef.shape = poly;
body.CreateFixture(fixtureDef);
}
private createWorld(){
var gravity:Box2D.Common.Math.b2Vec2 = new Box2D.Common.Math.b2Vec2(0,10);
this.world = new Box2D.Dynamics.b2World(gravity,true);
}
private createDebug(){
var s:egret.Sprite = new egret.Sprite();
this.addChild(s);
this.debug = new Box2D.Dynamics.b2DebugDraw();
this.debug.SetSprite(s);
this.debug.SetDrawScale(30);
this.debug.SetLineThickness(1);
this.debug.SetAlpha(0.8);
this.debug.SetFillAlpha(0.5);
this.debug.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit);
this.world.SetDebugDraw(this.debug);
}
private loop(e:egret.Event){
this.world.Step(1/60,10,10);
this.world.DrawDebugData();
}
}
*参考文档:
egret参考文档:http://edn.egret.com/cn/docs/page/172
第三方参考文档:http://www.ladeng6666.com/blog/2014/11/14/box2d-in-egret/