box2d入门教程
- 格式:pdf
- 大小:298.15 KB
- 文档页数:40
本篇开始,会介绍lufylegend-1.4.0的新功能,怎样结合box2dweb 创建一个物理世界以及这个物理世界里的各种刚体准备工作首先你需要下载html5开源库件lufylegend-1.4.0/lufy_legend/article/details/7644932box2dweb你可以到这里下载/p/box2dweb/downloads/list准备三张图片,分别用来创建圆形,矩形和三角刚体。
准备结束,现在开始制作。
下面是利用lufylegend.js中的LLoadManage类来读取图片[javascript]view plain copy1.init(10,"mylegend",800,400,main);2.var backLayer,cLayer,wallLayer,bitmap,loadingLayer;3.var imglist = {};4.var imgData = new Array(5. {name:"bird1",path:"./images/bird1.png"},6. {name:"bird2",path:"./images/bird2.png"},7. {name:"stage01",path:"./images/stage01.png"}8. );9.function main(){10. LGlobal.setDebug(true);11. backLayer = new LSprite();12. addChild(backLayer);13.14.15. loadingLayer = new LoadingSample3();16. backLayer.addChild(loadingLayer);17. LLoadManage.load(18. imgData,19.function(progress){20. loadingLayer.setProgress(progress);21. },22.function(result){23. imglist = result;24. backLayer.removeChild(loadingLayer);25. loadingLayer = null;26. gameInit();27. }28. );29.}LGlobal.setDebug(true);是开启debug模式,这样在创建刚体的时候,会将box2dweb所创建的debug刚体也一起显示出来,发布成品的时候,应该关闭debug模式。
Box2D v2.0.1 用户手册原文:Box2D v2.0.2 User Manual译者:Aman JIANG(江超宇),翻译信息。
1. 导言1.1 关于Box2D 是一个用于游戏的 2D 刚体仿真库。
程序员可以在他们的游戏里使用它,它可以使物体的运动更加可信,让世界看起来更具交互性。
从游戏的视角来看,物理引擎就是一个程序性动画(procedural animation)的系统,而不是由动画师去移动你的物体。
你可以让牛顿来做导演。
Box2D 是用可移植的 C++ 来写成的。
引擎中定义的大部分类型都有 b2 前缀,希望这能消除它和你游戏引擎之间的名字冲突。
1.2 必备条件在此,我假定你已经熟悉了基本的物理学概念,例如质量,力,扭矩和冲量。
如果没有,请先考虑读一下 Chris Hecker 和 David Baraff (google 这些名字)的那些教程,你不需要了解得非常细致,但他们可以使你很好地了解一些基本概念,以便你使用 Box2D。
Wikipedia 也是一个极好的物理和数学知识的获取源,在某些方面它可能比 google 更有用,因为它的内容经过了精心的整理。
这不是必要的,但如果你好奇 Box2D 内部是如何工作的,你可以看 这些文档。
因为 Box2D 是使用 C++ 写成的,所以你应该具备 C++ 程序设计的经验,Box2D 不应该成为你的第一个 C++ 程序项目。
你应该已经能熟练地编译,链接和调试了。
1.3 核心概念Box2D 中有一些基本的对象,这里我们先做一个简要的定义,在随后的文档里会有更详细的描述。
刚体(rigid body)一块十分坚硬的物质,它上面的任何两点之间的距离都是完全不变的。
它们就像钻石那样坚硬。
在后面的讨论中,我们用物体(body)来代替刚体。
形状(shape)一块严格依附于物体(body)的 2D 碰撞几何结构(collision geometry)。
形状具有摩擦(friction)和恢复(restitution)的材料性质。
box2d用法Box2D是一款非常流行的物理引擎,广泛应用于游戏开发、机器人模拟等领域。
它提供了一个简单而强大的API,可以模拟真实的物理世界,让开发者能够轻松地实现各种物理效果。
在本篇文章中,我们将介绍Box2D的基本用法,包括它的安装、基本概念和示例代码。
一、安装Box2D要使用Box2D,首先需要在开发环境中引入它的库。
通常情况下,Box2D提供了动态链接库(DLL)或静态库(.a文件),可以通过拖放或导入的方式将其添加到项目中。
此外,还需要在项目中链接相应的Box2D头文件。
二、基本概念1.物体(Body):Box2D中的物体表示物理世界中的对象,如墙壁、球体、刚体等。
物体由质量、形状和速度等属性描述。
2.关节(Joint):Box2D中的关节用于连接两个物体,以实现它们之间的相互作用。
常见的关节类型包括弹簧关节、固定关节和滑轮关节等。
3.边界(Shape):边界用于定义物体的形状和尺寸,以便在模拟中计算碰撞和受力。
Box2D提供了多种边界类型,如圆形边界、矩形边界和多边形边界等。
4.世界(World):世界是Box2D中的模拟环境,包含多个物体和关节。
开发者可以通过设置重力、模拟时间等参数来控制世界的行为。
三、示例代码下面是一个简单的Box2D示例代码,用于创建一个球体并模拟其运动:```cpp//创建世界b2World*world=newb2World();//创建球体b2BodyDefbodyDef;bodyDef.type=b2_dynamicBody;//动态球体bodyDef.position.Set(0.0f,10.0f);//球体位置b2Body*body=world->CreateBody(&bodyDef);//设置球体形状和摩擦力b2CircleShapecircle;circle.m_radius=0.5f;//球体半径body->CreateFixture(&circle,1.0f);//摩擦力系数为1.0f//模拟移动球体for(inti=0;i<100;i++){//更新世界时间步长world->Step(1.0f/60.0f,10,10);//设置球体的速度和角度变化body->SetLinearVelocity(b2Vec2(body->GetLinearVelocity().x*cos(i*(M_PI/180.0f)),body->GetLinearVelocity().y*sin(i*(M_PI/180.0f)));body->SetAngle(body->GetAngle()+i*(M_PI/180.0f);}```这段代码创建了一个动态球体,并在模拟中移动它。
第十章BOX2D 2D物理引擎能增强游戏世界中物体如多边形(箱子,三角形,多边形)的动作的真实感从而提高游戏质量。
这个引擎通过用户设定的参数如重力,密度,摩擦,弹性等参数计算碰撞,角度,力和动力等。
jbox2D物理引擎原版是采用C++编写的,后来扩展到java,as等多种版本。
著名手机游戏愤怒的小鸟便是采用jbox2D物理引擎。
不过java版得jbox2D引擎性能不如C++环境下运行的性能好。
在性能配置比较好的手机上面,jbox2D效果也是不错的。
•Box2D分为java版、C++版、Flash版:Box2D(主要用C++开发的APP和IOS)JBox2D(主要用于J2se、J2me、android)源码:库文件:/p/jbox2d/downloads/list物理世界与手机屏幕坐标系之间的关系•Box2D在Android 中的应用:下载类库/p/jbox2d/downloads/list建立android项目时,导入jbox的jar包。
jbox2D的使用步骤:1.创建一个World的世界在创建一个world对象之前,创建一个AABB的坐标范围,创建一个Vec2的重力方向向量,将两个属性添加到world对象当中去。
2.创建一个Ground(地面)的对象,并设置地面的一些属性,例如弹性,密度,摩擦力等,将地面添加到world对象中去。
3.创建一个Body(物体)对象,并设置物体的属性,如质量,密度等,将物体添加到world对象中。
4.模拟world。
一旦启动模拟world(世界),各个物体对象的属性只,如碰撞后的速度,方向等发生改变,将属性在view界面中不断画出来,就是看到的物理效果。
•例子//创建坐标系private AABB worldAABB;//创建一个世界private World world;worldAABB=new AABB();//上下界,以屏幕的左上方为原点,如果创建的刚体到达屏幕的边缘的话,会停止模拟worldAABB.lowerBound.set(-100.0f,-100.0f);//注意这里使用的是现实世界的单位worldAABB.upperBound.set(100.0f, 100.0f);Vec2 gravity = new Vec2(0.0f,10.0f);//实例化物理世界重力向量对象boolean doSleep= true;//创建世界world = new World(worldAABB, gravity, doSleep);worldAABB一个边界框,完全包含了所有你的形状。
Box2D 物理游戏编程基础内容Box2D 物理游戏编程基础 (1)致谢 (5)前言 (6)A.1 是否需要物理知识 (6)A.2 适用对象 (6)A.3 需要什么 (6)A.4 阅读规范 (7)1.认识Box2D世界 (8)1.1什么是Box2D引擎 (8)1.2 创建Box2D世界 (9)1.2.1 重力 (10)1.2.2 创建世界 (11)1.3 开启Box2D模拟 (12)1.4 小结 (16)2.认识刚体 (17)2.1 什么是刚体 (17)2.2创建刚体 (18)2.3 认识刚体形状 (24)圆形 (25)矩形 (25)2.4 b2DebugDraw调试视图 (28)2.5小结 (33)3.刚体属性详解 (34)3.1 b2BodyDef (34)状态类属性 (35)角度、角速度类属性 (38)坐标、速度类属性 (42)其他属性 (45)3.2 b2FixtureDef (48)物质特性类属性 (49)碰撞属性 (52)形状 (56)其他属性 (68)3.3 小结 (68)4.刚体操作 (70)4.1 LDEasyBox2D工具包 (70)4.2 CreateFixture (74)4.3 CreateFixture2 (77)4.4 DestroyFixture (78)4.5 ApplyForce (81)4.6 ApplyImpulse (86)4.7 ApplyTorque (89)4.8 GetLocalXXX、GetWorldXXX (92)4.9 GetMass (94)4.10 SetMassData (96)4.11 Split (99)4.12 GetAABB (102)4.13 QueryAABB (107)4.14 QueryShape (112)4.15 RayCast (119)4.16 小结 (128)5.碰撞处理 (129)5.1 认识碰撞 (129)5.2 b2Contact (131)GetFixtureA()和GetFixtureB() (132)GetManiFold() (133)GetWorldManifold() (135)isTouching() (137)SetEnabled()和IsEnabled() (137)SetSensor()和IsSensor() (139)SetFriction() (139)SetRestitution() (140)SetTangentSpeed() (141)5.3 b2ContactListener碰撞侦听器 (142)5.4 游戏中的碰撞处理 (146)万有引力 (147)小鸟冲量 (151)单边平台 (156)碰撞粘贴 (166)5.5 小结 (174)6.关节 (176)6.1 认识Box2D关节 (177)6.2 b2MouseJoint鼠标关节 (181)6.3 b2PrismaticJoint位移关节 (187)6.4 b2LineJoint线段关节 (193)6.5 b2RevoluteJoint旋转关节 (194)6.6 b2DistanceJoint距离关节 (200)6.7 b2WeldJoint粘贴关节 (204)6.8 b2PulleyJoint滑轮关节 (206)6.9 b2FrictionJoint 摩擦关节 (211)6.10 b2GearJoint 齿轮关节 (214)6.11 b2WheelJoint中轴关节 (218)6.12 b2RopeJoint绳索关节 (224)6.13 b2MotorJoint马达关节 (229)6.14 综合示例 (232)6.15 小结 (235)7.Box2D工具 (237)7.1 PhysicsEditor (237)7.2 RUBE (249)7.3 b2Separator (261)7.4 小结 (264)8. 游戏中的Box2D应用 (266)8.1 柔体 (266)相关知识点 (266)简单的柔体 (266)柔体库LiquidFun (270)8.2 浮力 (272)相关知识点 (273)水的浮力 (273)水的阻力 (280)8.3 刚体切割 (284)相关知识点 (285)切割的实现 (285)8.4 关节碰撞 (292)相关知识点 (293)关节的碰撞与折弯 (293)回摆的处理 (298)游戏交互 (309)完美的绳索 (313)8.5 小结 (314)附录:向量运算 (316)A.1 Box2D中的向量 (316)A.2 AddVV (316)A.3 SubtractVV (317)A.4 Normalize (317)A.5 NegativeSelf (318)A.6 Distance (318)A.7 Mul (319)MulFV (319)MulQV (319)MulMV (320)MulX (321)A.8 Cross (322)CrossVV (322)CrossFV (323)CrossVF (323)A.9 Dot (324)从起初开始执笔写这本书,到最终稿件的完成,中间经过了一年多的时间,在这段时间里,很多人都从不同的方面帮助着我,支持着我把这本书写完,我想我应该在本书开始之前,由衷的对这些帮助过我的人表示感谢。
【Cocos2dx开发】Box2D(一)【Cocos2dx开发】Box2D(一)写在前面——有不对的地方,请大家批评指正,我会继续努力提高自己。
如果转载请注明出处,谢谢大家支持——Forward。
我的微博——秦京一梦QQ技术交流群——forTheDream(225117179)Hello,Forward新一篇博客来啦~作为游戏开发人员为了使得游戏场景更加真实,不可回避地会面临物理世界的模拟,而Box2D作为一款帮助我们更加简单快捷的实现这一效果的物理引擎,已经被广泛使用。
比如市面上比较流行的游戏《愤怒的小鸟》就是一个经典的作品。
那么在Cocos2dx中,我们怎么才能使用Box2D来创建真是的物理世界呢?如何在这个物理世界中创建具有真实效果的物体呢?当两个物体发生碰撞,我们又如何检测到呢?带着上面的问题,我们开始有关Cocos2dx+Box2D的学习,这一篇博客中,Forward的学习计划如下(说明:Forward这里提到的都是以Cocos2dx为基础的):1、物理世界概念;2、 Box2D代码结构;3、物理世界和物体的创建;4、 Box2D碰撞检测;5、 Box2D碰撞检测Demo演示物理世界概念:这里我们引入“世界”的概念,一般来说一个游戏至少存在一个世界,比如在《坦克大战》中我们看到的整个矩形框就是一个游戏世界,这个世界里面包含了我方坦克、我方基地、敌方坦克以及障碍物等等世界中的物体对象。
又比如说经典游戏《魂斗罗》中,玩家控制的游戏对象通过躲避、击杀敌人等方式到达目的地进而通关的一款游戏,玩家控制对象所在的场景就是一个世界。
上面两款游戏中提到的世界,这里我们把它称作“渲染世界”,也就是玩家所能看到的场景。
为了让场景中的人物更好的模拟真实世界的碰撞、掉落、打击等等事件,这里我们要引入另外一个概念——物理世界。
将这两种世界结合就是我们今天要提到的Cocos2dx+Box2D的开发方式。
下面是一个简易的两个世界的交互图说明:Box2D代码结构:好的,了解了游戏世界的关系之后,我们接下来看看Cocos2dx 中对Box2D模块的代码结构。
1. Box2D v2.1.0用户手册翻译 - 目录,第01章 导言(Introduction)网上已经有个Box2D用户手册的翻译,但是基于v2.0.1,跟最新手册有很多不对应。
在这里决定将文档的全文再翻译出来,更准确的说是根据网上流传的v2.0.1版本,将最新文档重新整理一遍。
很多内容是直接复制自Aman JIANG(江超宇)翻译的Box2D v2.0.1 用户手册Box2D v2.1.0 用户手册版权 2007-2010 Erin Catto第01章 导言(Introduction)第02章 Hello Box2D第03章 公共模块(Common)第04章 碰撞模块(Collision Module)第05章 动态模块(Dynamics Module)第06章 夹具(Fixtures)第07章 物体(Bodies)第08章 关节(Joints)第09章 接触(Contacts)第10章 世界(World Class)第11章 杂项(Loose Ends)第12章 调试绘图(Debug Drawing)第13章 限制(Limitations)第14章 参考(References)第01章 导言(Introduction)1.1 关于Box2D是个二维刚体仿真库, 用于编写游戏。
程序员可以使用它, 让游戏中的物体运动起来更真实, 让游戏世界更具交互性。
以游戏的角度来看,物理引擎只是个程序性动画系统。
(procedural animation)(译注: 做动画常有两种方法, 一种是预先准备好动画所需的数据,比如图片,再一帧一帧地播放。
另一种是以一定方法,动态计算出动画所需的数据,根据数据再进行绘图。
从这种角度看,预先准备的,可称为数据性动画,动态计算的可称为程序性动画。
这个区别,就类似以前我们做历史题和数学题,做历史题,记忆很重要,也就是答案需要预先准备好的。
做数学题,方法就很重要,答案是需要用方法推导出来的。
BOX2D使用手册一,Fixture参数(夹具)Fillter 筛选Sensor 传感器Shape 形状Density 密度Resitution 恢复Userdata 使用者属性Friction 摩擦二,BodyDef参数(刚体)Type 模式Position 位置Angle 角度Linearvelocity 线性速度Angularvelocity 角速度Lineardamping 线性减震Angulardamping 角减震Allowsleep 允许休息Fixedrotation 固定角度Bullet 子弹Active 激活Userdata 使用者属性Gravityscale 重力比例,级别三,JointDef参数(关节)0.JointDefType 类型UserData 使用者属性BodyA 链接的第一个BODYBodyB 链接的第二个BODYCollideConnected 是否碰撞连接1.RevoluteJointDef 转动LocalAnchorA A连接点局部坐标LocalAnchorB B连接点局部坐标ReferenceAngle 参考角度EnableLimit 是否限制lowerAngle 最低角度UpperAngle 最高角度EnableMotor 是否用马达MotorSpeed 马达速度MaxMotorTorque 最大马达扭矩1.DistanceJointDef 距离LocalAnchorA A连接点局部坐标LocalAnchorB B连接点局部坐标Length 连接长度FreQuencyHz 频率DampingRatio 减震比率1.FrictionJointDef 摩擦LocalAnchorA A连接点局部坐标LocalAnchorB B连接点局部坐标MaxForce 最大力度MaxTorque 最大扭矩1.GearJointDef 齿轮Joint1 A连接点局部坐标Joint2 B连接点局部坐标Ratio 比率1.MouseJointDefTarget 标记MaxForce 最大力度FrequencyHz 频率DampingRatio 减震比率1.PracticeJointDef 实践LocalAnchorA A连接点局部坐标LocalAnchorB B连接点局部坐标LocalAxisA 局部轴AReferenceAngle 参考角度EnableLimit 是否限制LowerTranslation 最低平移UpperTranslation 最高平移EnableMotor 是否开启马达MaxMotorForce 最大马达力度MotorSpeed 马达速度1.PulletJointDef 滑轮GroundAnchorA A连接点局部坐标GroundAnchorB B连接点局部坐标LocalAnchorA 局部ALocanAnchorBLengthA 长度ALengthB 长度BRatio 比率1.RopeJoint 绳子LocalAnchorALocalAnchorBMaxlength1.WeldJointDef 焊接LocalAnchorALocalAnchorBReferenceAngle 参考角度1.WheelJoint 轮子LocalAnchorALocalAnchorBLocalAxisAEnableMotorMaxMotorTorqueMotorSpeedFrequencyHzDampingRatio 减震比率。
Box2DFlash v2.0.2User manualLargely cribbed unauthorized from the Box2D manual,copyright2007-2009Erin Catto. AboutBox2DFlash is a2D rigid body simulation library for games.Programmers can use it in their games to make objects move in believable ways and make the world seem more interactive.From the game's point of view a physics engine is just a system for procedural animation.Rather than paying(or begging)an animator to move your actors around,you can let Sir Isaac Newton do the directing.Box2DFlash is written in AS3,and resides in the Box2d namespace.Most of the types defined in the engine begin with the b2prefix,to match the C++version.PrerequisitesIn this manual I'll assume you are familiar with basic physics concepts,such as mass, force,torque(扭转力),and impulses(推力).If not,please first consult(翻阅)the many tutorials provided by Chris Hecker and David Baraff(google these names).You do not need to understand their tutorials in great detail,but they do a good job of laying out the basic concepts that will help you use Box2D.Wikipedia is also an excellent source of physics and mathematics knowledge.In some ways it is more useful than Google,because it has carefully crafted content.This is not a prerequisite,but if you are curious about the inner workings of Box2D,you can look at these articles.Since Box2DAS3is written in Actionscript3,you are expected to be experienced in this.If you come from an AS2background,you may find it easier to start on an easier project before using Box2D,but it is not impossible.Core ConceptsBox2D works with several fundamental objects.We briefly define these objects here and more details are given later in this document.rigid body(刚体)A chunk of matter(物质)that is so strong that the distance between any two bits ofmatter on the chunk is completely constant.They are hard like a diamond.In the following discussion we use body interchangably with rigid body.shapeA2D piece of collision geometry that is rigidly attached to a body.Shapes have material properties of friction and restitution.(依附于body的2d碰撞几何结构,具有摩擦和恢复特性)Constraint(约束)A constraint is a physical connection that removes degrees of freedom from bodies.In2D a body has3degrees of freedom.If we take a body and pin it to the wall(like a pendulum)we have constrained the body to the wall.At this point the body can only rotate about the pin,so the constraint has removed2degrees of freedom.contact constraint(接触约束)A special constraint designed to prevent penetration(穿透)of rigid bodies and tosimulate(模仿)friction and restitution.You will never create a contact constraint,they are created automatically by Box2D.jointThis is a constraint used to hold two or more bodies together.Box2D supports these joint types:revolute,prismatic,distance,and more.Joints may support limits and motors.joint limitA joint limit restricts the range of motion of a joint.For example,the human elbow onlyallows a certain range of angles.joint motorA joint motor drives the motion of the connected bodies according to the joint'sdegrees of freedom.For example,you can use a motor to drive the rotation of an elbow.worldA physics world is a collection of bodies,shapes,and constraints that interact together.Box2D supports the creation of multiple worlds,but this is usually not necessary or desirable.Hello Box2DThis is a small example program that creates a large ground box and a small dynamic box. This code does not contain any graphics,so prepare to be underwelmed.:).The matching documents for this example have yet to be created.Creating a WorldEvery Box2D program begins with the creation of a world object.This is the physics hub that manages objects,and simulation.To create a world object,first we need to define a bounding box for the world.Box2D uses the bounding box to accelerate collision detection.The size isn't critical,but a better fit will improve performance.It is better to make the box too big than to make it too small.view sourceprint?1varworldAABB:b2AABB=newb2AABB();2worldAABB.lowerBound.Set(-100.0,-100.0);3worldAABB.upperBound.Set(100.0,100.0);CautionThe world AABB should always be bigger then the region where your bodies are located. It is better to make the world AABB too big than too small.If a body reaches the boundary of the world AABB it will be frozen and will stop simulating.Next we define the gravity vector.Yes,you can make gravity go sideways(or you could just rotate your monitor).Also we tell the world to allow bodies to sleep when they come to rest.A sleeping body doesn't require any simulation.view sourceprint?1vargravity:b2Vec2=newb2Vec2(0.0,-10.0);2vardoSleep:Boolean=true;Now we create the world object.view sourceprint?1varworld:b2World=newb2World(worldAABB,gravity,doSleep);So now we have our physics world,let's start adding some stuff to it.Creating a Ground BoxBodies are built using the following steps:1Define a body with a position,damping,etc.2Use the world object to create the body.3Define shapes with geometry,friction,density,etc.4Create shapes on the body.5Optionally adjust the body's mass to match the attached shapes.For step1we create the ground body.For this we need a body definition.With the body definition we specify the initial position of the ground body.view sourceprint?1vargroundBodyDef:b2BodyDef=newb2BodyDef();2groundBodyDef.position.Set(0.0,-10.0);For step2the body definition is passed to the world object to create the ground body. The world object does not keep a reference to the body definition.The ground body is created as a static body.Static bodies don't collide with other static bodies and are immovable.Box2D determines that a body is static when it has zero mass.Bodies have zero mass by default,therefore they are static by default.view sourceprint?1vargroundBody:b2Body=world.CreateBody(groundBodyDef);For step3we create a ground polygon definition.We use the SetAsBox shortcut to formthe ground polygon into a box shape,with the box centered on the origin of the parent body.view sourceprint?1vargroundShapeDef:b2PolygonDef=newb2PolygonDef();2groundShapeDef.SetAsBox(50.0,10.0);The SetAsBox function takes the half-width and half-height.So in this case the ground box is100units wide(x-axis)and20units tall(y-axis).Box2D is tuned for meters, kilograms,and seconds.So you can consider the extents to be in meters.However,it is possible to change unit systems,as discussed later in this document.We finish the ground body in step4by creating the ground polygon shape on the ground body.view sourceprint?1groundBody.CreateShape(groundShapeDef);Again,Box2D does not keep a reference to the shape or body definitions.It copies the data into the b2Body structure.Note that every shape must have a parent body,even shapes that are static.However, you can attach all static shapes to a single static body.This need for static bodies is done to make the Box2D code more uniform internally,reducing the number of potential bugs.You might notice a pattern here.Most Box2D types are prefixed with b2.This is done to reduce the chance for naming conflicts with your code.Creating a Dynamic BodySo now we have a ground body.We can use the same technique to create a dynamic body.The main difference,besides dimensions,is that we must establish the dynamic body's mass properties.First we create the body using CreateBody.view sourceprint?1varbodyDef:b2BodyDef=newb2BodyDef();2bodyDef.position.Set(0.0,4.0);34varbody:b2Body=world.CreateBody(bodyDef);Next we create and attach a polygon shape.Notice that we set density to1.The default density is zero.Also,the friction on the shape is set to0.3.Once the shape is attached, we instruct the body to compute it's mass properties from the attached shapes using the method SetMassFromShapes.This gives you a hint that you can attach more than one shape per body.If the computed mass is zero,then the body becomes truly static.Bodies have a mass of zero by default,that's why we didn't need to call SetMassFromShapes for the ground body.view sourceprint?1varshapeDef:b2PolygonDef=newb2PolygonDef();2shapeDef.SetAsBox(1.0,1.0);3shapeDef.density=1.0;4shapeDef.friction=0.3;5body.CreateShape(shapeDef);6body.SetMassFromShapes();That's it for initialization.We are now ready to begin simulating.Simulating the World(of Box2D)So we have initialized the ground box and a dynamic box.Now we are ready to set Newton loose to do his thing.We just have a couple more issues to consider.Box2D uses a bit of numerical code called an integrator.Integrators simulate the physics equations at discrete points of time.This goes along with the traditional game loop where we essentially have a flip book of movement on the screen.So we need to pick a time step for Box2D.Generally physics engines for games like a time step at least as fast as60Hz or1/60seconds.You can get away with larger time steps,but you will have to be more careful about setting up the definitions for your world.We also don't like the time step to change much.So don't tie the time step to your frame rate(unless you really,really have to).Without further ado,here is the time step.view sourceprint?1vartimeStep:Number=1.0/60.0;In addition to the integrator,Box2D also uses a larger bit of code called a constraint solver.The constraint solver solves all the constraints in the simulation,one at a time.A single constraint can be solved perfectly.However,when we solve one constraint,we slightly disrupt other constraints.To get a good solution,we need to iterate over all constraints a number of times.The suggested iteration count for Box2D is10.You can tune this number to your liking,just keep in mind that this has a trade-off between speed and ing fewer iterations increases performance but accuracy suffers. Likewise,using more iterations decreases performance but improves the quality of your simulation.Here is our chosen iteration count.view sourceprint?1variterations:Number=10;Note that the time step and the iteration count are completely unrelated.An iteration is not a sub-step.One iteration is a single pass over all the constraints withing a time step. You can have multiple passes over the constraints within a single time step.We are now ready to begin the simulation loop.In your game the simulation loop can be merged with your game loop.In each pass through your game loop you call b2World.Step.Just one call is usually enough,depending on your frame rate and your physics time step.The Hello World program was designed to be dead simple,so it has no graphical output. Rather that being utterly boring by producing no output,the code prints out the position and rotation of the dynamic body.Yay!Here is the simulation loop that simulates60time steps for a total of1second of simulated time.view sourceprint?1for(vari:Number=0;i<60;++i)23{4world.Step(timeStep,iterations);5varposition:b2Vec2=body.GetPosition();6varangle:Number=body.GetAngle();7trace(position.x+','+position.y+','+angle);89}The TestbedOnce you have conquered the HelloWorld example,you should start looking at Box2DAS3's testbed.The testbed is a unit-testing framework and demo environment. Here are some of the features:•Mouse picking of shapes attached to dynamic bodies.•Extensible set of tests.The testbed has many examples of Box2D usage in the test cases and the framework itself.I encourage you to explore and tinker with the testbed as you learn Box2D.API DesignMemory ManagementBox2dFlash is a straight port of Box2D,a C++library.Hence in many places,memory is managed precisely,rather than relying on the garbage collector.This helps reduce stutter. Objects are recycled,hence the many Create/Destroy methods.Factories and DefinitionsAs mentioned above,memory management plays a central role in the design of the Box2D API.So when you create a b2Body or a b2Joint,you need to call the factoryfunctions on b2World.There are creation functions:view sourceprint?1b2World.CreateBody(def:b2BodyDef):b2Body2b2World.CreateJoint(def:b2JointDef):b2JointAnd there are corresponding destruction functions:view sourceprint?1b2World.DestroyBody(body:b2Body):void23b2World.DestroyJoint(joint:b2Joint):voidWhen you create a body or joint,you need to provide a definition or def for short. These definitions contain all the information needed to build the body or joint.By using this approach we can prevent construction errors,keep the number of function parameters small,provide sensible defaults,and reduce the number of accessors.Since shapes must be parented to a body,they are created and destroyed using a factory method on b2Body:view sourceprint?1b2Body.CreateShape(def:b2ShapeDef):b2Shape2b2Body.DestroyShape(shape:b2Shape):voidFactories do not retain references to the definitions.So you can create definitions on the stack and keep them in temporary resources.UnitsBox2D works with floating point numbers,so some tolerances have to be used to make Box2D perform well.These tolerance have been tuned to work well with meters-kilogram-second(MKS)units.In particular,Box2D has been tuned to work well with moving objects between0.1and10meters.So this means objects between soup cans and buses in size should work well.Being a2D physics engine it is tempting to use pixels as your units.Unfortunately this will lead to a poor simulation and possibly weird behavior.An object of length200pixels would be seen by Box2D as the size of a45story building.Imagine trying to simulate the movement of a high-rise building with an engine that is tuned to simulate ragdolls and barrels.It isn't pretty.***Caution***Box2D is tuned for MKS units.Keep the size of moving objects roughly between0.1and10meters.You'll need to use some scaling system when you render your environment and actors.The built in DebugDraw already features a scaling factor.User DataThe b2Shape,b2Body,and b2Joint classes allow you to attach any object as user data. This is handy when you are examining Box2D data structures and you want to determine how they relate to the data structures in your game engine.For example,it is typical to attach an actor to the rigid body on that actor.This sets up a circular reference.If you have the actor,you can get the body.If you have the body,you can get the actor.view sourceprint?1actor:GameActor=newGameCreateActor();2bodyDef:b2BodyDef=newb2BodyDef();erData=actor;4actor.body=box2Dworld.CreateBody(bodyDef);Here are some examples of cases where you would need the user data:•Applying damage to an actor using a collision result.•Playing a scripted event if the player is inside an axis-aligned box.•Accessing a game structure when Box2D notifies you that a joint is going to be destroyed.Keep in mind that user data is optional and you can put anything in it.However,you should be consistent.For example,if you want to store an actor on one body,you should probably keep an actor on all bodies.StrawmanIf you don't like this API design,that's ok!You have the source code!Seriously,if you have feedback about anything related to Box2D,please leave a comment in the forum.The WorldAboutThe b2World class contains the bodies and joints.It manages all aspects of the simulation and allows for asynchronous queries(like AABB queries).Much of your interactions with Box2D will be with a b2World object.Creating and Destroying a WorldCreating a world is fairly simple.You need to provide a bounding box and a gravity vector.The axis-aligned bounding box should encapsulate the world.You can improve performance by making the bounding box a bit bigger than your world,say2x just to be safe.If you have lots of bodies that fall into the abyss,your application should detect this and remove the bodies.This will improve performance and prevent floating point overflow.view sourceprint?1varmyWorld:b2World=newb2World(aabb,gravity,doSleep)When myWorld goes out of use,it will automatically be deleted by the garbage collector.CautionRecall that the world AABB should always be bigger then the region where your bodies are located.If bodies leave the world AABB,then they will be frozen.This is not a bug.Using a WorldThe world class contains factories for creating and destroying bodies and joints.These factories are discussed later in the sections on bodies and joints.There are some other interactions with b2World that I will cover now.SimulationThe world class is used to drive the simulation.You specify a time step and an iteration count.For example:view sourceprint?1vartimeStep:Number=1.0/60.;2variterationCount:Number=10;3myWorld.Step(timeStep,iterationCount);After the time step you can examine your bodies and joints for information.Most likely you will grab the position off the bodies so that you can update your actors and render them.You can perform the time step anywhere in your game loop,but you should be aware of the order of things.For example,you must create bodies before the time step if you want to get collision results for the new bodies in that frame.As I discussed above in the HelloWorld tutorial,you should use a fixed time step.By using a larger time step you can improve performance in low frame rate scenarios.But generally you should use a time step no larger than1/30seconds.A time step of1/60 seconds will usually deliver a high quality simulation.The iteration count controls how many times the constraint solver sweeps over all the contacts and joints in the world.More iterations always yields a better simulation.But don't trade a small time step for a large iteration count.60Hz and10iterations is far better than30Hz and20iterations.Exploring the WorldAs mentioned before,the world is a container for bodies and joints.You can grab the body and joint lists off the world and iterate over them.For example,this code wakes up all the bodies in the world.view sourceprint?1for(varb:b2Body=myWorld.GetBodyList();b;b=b.GetNext())23{4 b.WakeUp();5}Unfortunately life can be more complicated.For example,the following code is broken:view sourceprint?01for(varb:b2Body=myWorld.GetBodyList();b;b=b.GetNext())0203{04varmyActor:GameActor=b->GetUserData()asGameActor;05if(myActor.IsDead())06{07myWorld.DestroyBody(b);//ERROR:now GetNext returns garbage. 0809}10}Everything goes ok until a body is destroyed.Once a body is destroyed,its next pointer becomes invalid.So the call to b2Body.GetNext()will return garbage.The solution to this is to copy the next body before destroying the body.view sourceprint?01varnode:b2Body=myWorld.GetBodyList();02while(node)0304{05varb:b2Body=node;06node=node.GetNext();0708varmyActor:GameActor=b->GetUserData()asGameActor;09if(myActor.IsDead())1011{12myWorld.DestroyBody(b);13}14}This safely destroys the current body.However,you may want to call a game function that may destroy multiple bodies.In this case you need to be very careful.The solution is application specific,but for convenience I'll show one method of solving the problem.view sourceprint?01varnode:b2Body=myWorld.GetBodyList();02while(node)0304{05varb:b2Body=node;06node=node.GetNext();0708varmyActor:GameActor=b.GetUserData()asGameActor;09if(myActor.IsDead())1011{12varotherBodiesDestroyed:Boolean=GameCrazyBodyDestroyer(b); 13if(otherBodiesDestroyed)14{1516node=myWorld.GetBodyList();17}18}19}Obviously to make this work,GameCrazyBodyDestroyer must be honest about what it has destroyed.AABB QueriesSometimes you want to determine all the shapes in a region.The b2World class has a fast log(N)method for this using the broad-phase data structure.You provide an AABB in world coordinates and b2World returns an array of all the shapes that potentially intersect the AABB.This is not exact because what the function actually does is return all the shapes whose AABBs intersect the specified AABB.For example,the following code finds all the shapes that potentially intersect a specified AABB and wakes up all of the associated bodies.view sourceprint?01varaabb:b2AABB=newb2AABB();02aabb.lowerBound.Set(-1.0,-1.0);03aabb.upperBound.Set(1.0,1.0);0405vark_bufferSize:Number=10;06varbuffer:Array=[];07varcount:Number=myWorld.Query(aabb,buffer,k_bufferSize);0809for(vari:Number=0;i<count;++i)10{11buffer[i].GetBody().WakeUp();1213}Note:This calling syntax is rather obscure for typical AS3use.This is due to Box2DAS3's C++heritage,which does not handle variable sized arrays so easily.BodiesAboutBodies have position and velocity.You can apply forces,torques,and impulses to bodies. Bodies can be static or dynamic.Static bodies never move and don't collide with other static bodies.Bodies are the backbone for shapes.Bodies carry shapes and move them around in the world.Bodies are always rigid bodies in Box2D.That means that two shapes attached to the same rigid body never move relative to each other.You usually keep pointers to all the bodies you create.This way you can query the body positions to update the positions of your graphical entities.You should also keep body pointers so you can destroy them when you are done with them.Body DefinitionBefore a body is created you must create a body definition(b2BodyDef).You can create a body definition on the stack or build it into your game's data structures.The choice is up to you.Box2D copies the data out of the body definition,it does not keep a pointer to the body definition.This means you can recycle a body definition to create multiple bodies.Lets go over some of the key members of the body definition.Mass PropertiesThere are a few ways to establish the mass properties for a body.6Set the mass properties explicitly in the body definition.7Set the mass properties explicitly on the body(after it has been created).8Set the mass properties based on the density of the attaced shapes.In many game scenarios it makes sense to compute mass based on shape densities.This helps to ensure that bodies have reasonable and consistent mass values.However,other game scenarios may require specific mass values.For example,you may have a mechanism,like a scale that needs precise mass values.You can explicitly set the mass properties in the body definition as follows:view sourceprint?1bodyDef.massData.mass=2.0;//the body's mass in kg23bodyDef.massData.center.SetZero();//the center of mass in local coordinates4bodyDef.massData.I=3.0;//the rotational inertia in kg*m^2.The other methods of setting the mass properties are covered elsewhere in this document.Position and AngleThe body definition gives you the chance to initialize the position of the body on creation. This has better performance than creating the body at the world origin and then moving the body.A body has two main points of interest.The first point is the body's origin.Shapes and joints are attached relative to the body's origin.The second point of interest is the center of mass.The center of mass is determined from mass distribution of the attached shapes or is explicitly set with b2MassData.Much of Box2D's internal computations use the center of mass position.For example b2Body stores the linear velocity for the center of mass.When you are building the body definition,you may not know where the center of mass is located.Therefore you specify the position of the body's origin.You may also specify the body's angle in radians,which is not affected by the position of the center of mass.If you later change the mass properties of the body,then the center of mass may move on the body,but the origin position does not change and the attached shapes and joints do not move.view sourceprint?1bodyDef.position.Set(0.0,2.0);//the body's origin position.2bodyDef.angle=0.25*b2Settings.b2_pi;//the body's angle in radians.DampingDamping is used to reduce the world velocity of bodies.Damping differs from friction in that friction only occurs when two surfaces are in contact.Damping is also much cheaper to simulate than friction.Note,however,that damping is not a replacement for friction; the two effects should be used together.Damping parameters should be between0and infinity,with0meaning no damping,and infinity meaning full damping.Normally you will use a damping value between0and1.0.I generally do not use linear damping because it makes bodies look floaty.view sourceprint?1bodyDef.linearDamping=0.0;2bodyDef.angularDamping=0.1;Damping is approximated for stability and performance.At small damping values the damping effect is mostly independent of the time step.At larger damping values,the damping effect will vary with the time step.This is not an issue if you use a fixed time step(recommended).Sleep ParametersWhat does sleep mean?Well it is expensive to simulate bodies,so the less we have to simulate the better.When a body comes to rest we would like to stop simulating it.When Box2D determines that a body(or group of bodies)has come to rest,the body enters a sleep state which has very little CPU overhead.If an awake body collides with a sleeping body,then the sleeping body wakes up.Bodies will also wake up if a joint or contact attached to them is destroyed.You can also wake a body manually.The body definition lets you specify whether a body can sleep and whether a body is created sleeping.view sourceprint?1bodyDef.allowSleep=true;2bodyDef.isSleeping=false;BulletsGame simulation usually generates a sequence of images that are played at some frame rate.In this setting rigid bodies can move by a large amount in one time step.If a physics engine doesn't account for the large motion,you may see some objects incorrectly pass through each other.This effect is called tunneling.By default,Box2D uses continuous collision detection(CCD)to prevent dynamic bodies from tunneling through static bodies.This is done by sweeping shapes from their old position to their new positions.The engine looks for new collisions during the sweep andcomputes the time of impact(TOI)for these collisions.Bodies are moved to their first TOI and then simulated to the end of the original time step.This process is repeated as necessary.Normally CCD is not used between dynamic bodies.This is done to keep performance reasonable.In some game scenarios you need dynamic bodies to use CCD.For example, you may want to shoot a high speed bullet at a thin wall.Without CCD,the bullet my tunnel through the wall.Fast moving objects in Box2D are called bullets.You should decide what bodies should be bullets based on your game design.If you decide a body should be treated as a bullet, use the following setting.view sourceprint?1bodyDef.isBullet=true;The bullet flag only affects dynamic bodies.CCD is expensive so you probably don't want all moving bodies to be bullets.So by default Box2D only uses CCD between moving bodies and static bodies.This is an effective approach to prevent bodies from escaping your game world.However,you may have some fast moving bodies that that require CCD all the time.Body FactoryBodies are created and destroyed using a body factory provided by the world class.This lets the world create the body with an efficient allocator and add the body to the world data structure.Bodies can be dynamic or static depending on the mass properties.Both body types use the same creation and destruction methods.view sourceprint?1vardynamicBody:b2Body=myWorld.CreateBody(bodyDef);23//...do stuff...4myWorld.DestroyBody(dynamicBody);5dynamicBody=null;Static bodies do not move under the influence of other bodies.You may manually move static bodies,but you should be careful so that you don't squash dynamic bodies between two or more static bodies.Friction will not work correctly if you move a static body.Static bodies never simulate on their own and they never collide with other static bodies.It is faster to attach several shapes to a static body than to create several static bodies with a single shape on each one.Internally,Box2D sets the mass and inverse mass of static bodies to zero.This makes the math work out so that most algorithms。