01.Box2dWeb入门教程
1.下载box2dweb.直接在页面中引用即可。
-Box2D.js是未压缩版
-Box2d.min.js是压缩版
2.编写HelloWorld代码。
<!DOCTYPE HTML> <html> <head> <title>LaiXiao Box2DWeb Test</title> <script type="text/javascript" src="js/Box2D.js"></script> </head> <body onload="init();"> <canvas id="canvas" width="600" height="400" style="background-color:#333333;"></canvas> <script> function init(){ //方便使用 var b2Vec2 = Box2D.Common.Math.b2Vec2, b2BodyDef = Box2D.Dynamics.b2BodyDef, b2Body = Box2D.Dynamics.b2Body, b2FixtureDef = Box2D.Dynamics.b2FixtureDef, b2Fixture = Box2D.Dynamics.b2Fixture, b2World = Box2D.Dynamics.b2World, b2MassData = Box2D.Collision.Shapes.b2MassData, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape, b2DebugDraw = Box2D.Dynamics.b2DebugDraw; //1.创建一个世界 var world = new b2World(new b2Vec2(0,9.8),true); //2.创建一个矩形刚体 //定义一个材质 var fixDef = new b2FixtureDef; fixDef.density = 1.0;//密度 fixDef.friction = 0.5;//摩擦 fixDef.restitution = 0.2;//弹性 fixDef.shape = new b2PolygonShape;//矩形 fixDef.shape.SetAsBox(5, 0.5);//宽高 //创建一个矩形地板刚体 var bodyDef = new b2BodyDef; bodyDef.type = b2Body.b2_staticBody;//静态的 bodyDef.position.x = 10; //X轴 bodyDef.position.y = 13; //Y轴 //世界中添加一个刚体 world.CreateBody(bodyDef).CreateFixture(fixDef); //3.同上创建一个圆形刚体 var fixDef2 = new b2FixtureDef; fixDef2.density = 1.0; fixDef2.friction = 0.5; fixDef2.restitution = 0.2; fixDef2.shape = new b2CircleShape(1); var bodyDef2 = new b2BodyDef; bodyDef2.type = b2Body.b2_dynamicBody; bodyDef2.position.x = 9; bodyDef2.position.y = 1; world.CreateBody(bodyDef2).CreateFixture(fixDef2); //4.setup debug draw var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")); debugDraw.SetDrawScale(30.0); debugDraw.SetFillAlpha(0.3); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); //5.一帧帧执行 window.setInterval(update, 1000 / 60); function update() { //Take a time step. world.Step( 1 / 60 //frame-rate , 10 //velocity iterations , 10 //position iterations ); //Call this to draw shapes and other debug draw data. world.DrawDebugData(); //Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps. world.ClearForces(); //console.log(111); }; } </script> </body> </html>
原创文章请随便转载。愿和大家分享,并且一起进步。-- 江 coder