当前位置: 首页 > Web前端 > HTML5

使用P2物理引擎制作实体球

时间:2023-04-05 13:50:07 HTML5

今天分享的内容是:基于Egret,使用P2物理引擎实现实体球的实例效果。更多信息可以查看P2物理引擎GitHub地址或EgretP2物理系统文档。第三方库的介绍创建一个P2物理工程一、第三方库的介绍1.首先新建一个工程。2、在GitHub上下载包括P2物理引擎库在内的完整第三方库,解压后根据路径找到物理模块。3.将physics模块放在与新建工程根目录同级目录下。4.修改egretProperties.json,在modules数组中添加{"name":"physics","path":"../physics"}5.然后找到插件-Egret项目工具-编译引擎并编译成功导入P2库,如下图。2.创建P2物理工程使用P2物理引擎创建物理应用的过程大致分为5个步骤:1.创建world世界2.创建shapeshape3.创建body刚体4.调用步骤()函数实时更新物理模拟计算5.基于形状和刚体,使用Egret渲染显示物理模拟效果。以下5个步骤用于构建代码。1.打开Main.ts,先创建一个worldworld//创建一个Wordworldprivateworld:p2.World;privateCreateWorld(){this.world=newp2.World();//将世界设置为睡眠状态this.world.睡眠模式=p2.World.BODY_SLEEPING;this.world.gravity=[0,1]}gravity是一个Vector2向量对象,代表world世界的重力加速度,默认为垂直向上的向量[0,-9.81],设置重力Gravity可以取消对于[0,0];重力的x分量也很有意义。设置为非零值后,重力会向[x,y]的方向移动。2.CreatethefloorPlane//生成floorPlaneprivateplaneBody:p2.Body;privateCreatePlane(){//创建一个形状letplaneShape:p2.Plane=newp2.Plane();//创建刚体刚体this.planeBody=newp2.Body({//刚体类型type:p2.Body.STATIC,//刚体位置position:[0,this.stage.stageHeight]});this.planeBody.angle=Math.PI;this.planeBody.displays=[];this.planeBody.addShape(planeShape);this.world.addBody(this.planeBody);}Plane相当于地面,默认面向Y轴。因为这个Y轴是P2的Y轴,不是Egret的Y轴。P2和Egret的Y轴是相反的。所以将地面翻转180度。planeBody.angle=Math.PI3。点击创建足球或矩形框privateshpeBody:p2.Body;//纹理显示对象privatedisplay:egret.DisplayObject;privateonButtonClick(e:egret.TouchEvent){if(Math.random()>0.5){//添加一个方形刚体varboxShape:p2.Shape=newp2.Box({width:140,height:80});this.shpeBody=newp2.Body({mass:1,position:[e.stageX,e.stageY],angularVelocity:1});this.shpeBody.addShape(boxShape);this.world.addBody(this.shpeBody);this.display=this.createBitmapByName("rect_png");this.display.width=(boxShape).widththis.display.height=(boxShape).height}else{//添加一个圆形刚体varcircleShape:p2.Shape=newp2.Circle({半径:60});this.shpeBody=newp2.Body({mass:1,position:[e.stageX,e.stageY]});this.shpeBody.addShape(circleShape);this.world.addBody(this.shpeBody);this.display=this.createBitmapByName("circle_png");this.display.width=(circleShape).radius*2this.display.height=(circleShape).radius*2}this.display.anchorOffsetX=this.display.width/2this.display.anchorOffsetY=this.display.height/2;this.display.x=-100;this.display.y=-100;this.display.rotation=270this.shpeBody.displays=[this.display];this.addChild(this.display);}在上面的代码中,首先创建一个Box或者Circle形状,通过addShape()函数将其添加到刚体中,最后将刚体添加到刚体中body通过world的addBody()在world中,完成一个P2物理应用的创建注意:Egret中加载的图片原点默认是左上角,而P2中刚体的原点是在它的中心,如下图(盗图),所以需要根据刚体的重量心坐标偏移(offsetX,offsetY)设置图像的anchorOffsetX和anchorOffsetY属性。4.frame函数实时调用step()函数//frameevent,stepfunctionprivateupdate(){this.world.step(2.5);varl=this.world.bodies.length;for(vari:number=0;i