小球越来越多那个游戏菜鸟|使用P2物理引擎制作物理小球

写在前面:随着越来越多的新人开始接触白鹭引擎,创作属于自己的游戏。考虑到初学者会遇到一些实际操作问题,我们近期整理推出“菜鸟”系列技术文档,以便更好的让这些开发者们快速上手,Egret大神们可以自动忽略此类内容。 本次我们将分享使用P2物
原标题:菜鸟|使用P2物理引擎制作物理小球写在前面:随着越来越多的新人开始接触白鹭引擎,创作属于自己的游戏。考虑到初学者会遇到一些实际操作问题,我们近期整理推出“菜鸟”系列技术文档,以便更好的让这些开发者们快速上手,Egret大神们可以自动忽略此类内容。本次我们将分享使用P2物理引擎实现物理小球示例效果。了解更多信息,您可以查看P2物理引擎GitHub地址或者是EgretP2物理系统文档。第三方库的引入创建一个P2物理项目一.第三方库的引入首先新建一个项目。在GitHub上下载包括P2物理引擎库的完整第三方库,解压后按照路径找到physics模块。将physics模块放到新建项目根目录的同级目录。修改egretProperties.json,modules数组里增加{\"name\":\"physics\",\"path\":\"../physics\"}然后找到插件-Egret项目工具-编译引擎编译一下就成功引入P2库,如下图。二.创建一个P2物理项目使用P2物理引擎创建物理应用的过程大致分为5个步骤:创建world世界创建shape形状创建body刚体实时调用step()函数,更新物理模拟计算基于形状、刚体,使用Egret渲染,显示物理模拟效果下面根据这5个步骤进行代码构建。1.打开Main.ts,首先创建world世界//创建Word世界privateworld:p2.World;privateCreateWorld(){this.world=newp2.World();//设置world为睡眠状态this.world.sleepMode=p2.World.BODY_SLEEPING;this.world.gravity=[0,1]}gravity是一个Vector2向量对象,表示world世界中重力加速度,默认为垂直向上的向量[0,-9.81],将gravity设置为[0,0]可以取消重力;gravity的x分量也是有意义的,将其设置为一个非0数值后,重力就会朝向量[x,y]方向。2.创建地板Plane//生成地板PlaneprivateplaneBody:p2.Body;privateCreatePlane(){//创建一个shape形状letplaneShape:p2.Plane=newp2.Plane();//创建body刚体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({radius: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()将刚体添加到世界中,完成一个P2物理应用创建。注意:Egret中加载进来的图像,其原点默认为左上角,而P2中刚体的原点处于其中心位置,如下图(盗了一张图)所以需要根据刚体重心坐标偏移量(offsetX,offsetY)设置图像的anchorOffsetX,anchorOffsetY属性。4.帧函数实时调用step()函数//帧事件,步函数privateupdate(){this.world.step(2.5);varl=this.world.bodies.length;for(vari:number=0;i

本文来自投稿,不代表长河网立场,转载请注明出处: http://www.changhe99.com/a/oRr8MWDkwX.html

(0)

相关推荐