Egret社区
本帖最后由 熊猫少女 于 2018-10-8 16:23 编辑

P2物理引擎——物理小球案例
本教程使用P2物理引擎实现了Egret官方的物理小球示例效果。如有不懂可以查看P2物理引擎GitHub地址或者是EgretP2物理系统文档
  • 第三方库的引入
  • 创建一个P2物理项目

1.  第三方库的引入
  • 首先新建一个项目。
  • GitHub上下载包括P2物理引擎库的完整第三方库,解压后按照路径找到physics模块。
  • 将physics模块放到新建项目根目录的同级目录。
  • 修改egretProperties.json,modules数组里增加
    {  "name":"physics",  "path":"../physics"}
  • 然后找到插件-Egret项目工具-编译引擎编译一下就成功引入P2库,如下图。

2.创建一个P2物理项目
使用P2物理引擎创建物理应用的过程大致分为5个步骤:
  • 创建world世界
  • 创建shape形状
  • 创建body刚体
  • 实时调用step()函数,更新物理模拟计算
  • 基于形状、刚体,使用Egret渲染,显示物理模拟效果



下面根据这5个步骤进行代码构建。
1.打开Main.ts,首先创建world世界//创建Word世界
[mw_shl_code=applescript,true]private world:p2.World;
private CreateWorld(){
    this.world = new p2.World();
    //设置world为睡眠状态
    this.world.sleepMode = p2.World.BODY_SLEEPING;
    this.world.gravity = [0,1]
}[/mw_shl_code]
gravity是一个Vector2向量对象,表示world世界中重力加速度,默认为垂直向上的向量[0,-9.81],将gravity设置为[0,0]可以取消重力;gravity的x分量也是有意义的,将其设置为一个非0数值后,重力就会朝向量[x,y]方向。
2.创建地板Plane[mw_shl_code=applescript,true]//生成地板Plane
private planeBody:p2.Body;
private CreatePlane(){
    //创建一个shape形状
    let planeShape:p2.Plane = new p2.Plane();
    //创建body刚体
    this.planeBody= new p2.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);
}[/mw_shl_code]
Plane相当于地面,默认面向Y轴方向。因为这个Y轴是P2的Y轴,而不是Egret的Y轴。P2和Egret的Y轴是相反的。所以将地面翻转180度。planeBody.angle = Math.PI
3.点击创建足球或者矩形方块
[mw_shl_code=applescript,true]private shpeBody:p2.Body;
//贴图显示对象
private display:egret.DisplayObject;
private onButtonClick(e:egret.TouchEvent) {
    if(Math.random() >0.5){
        //添加方形刚体
        var boxShape:p2.Shape = new p2.Box({width:140 ,height:80});
        this.shpeBody = new p2.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 = (<p2.Box>boxShape).width
        this.display.height = (<p2.Box>boxShape).height               
    }
    else{
        //添加圆形刚体
        var circleShape:p2.Shape = new p2.Circle({radius:60});
        this.shpeBody = new p2.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 = (<p2.Circle>circleShape).radius * 2
        this.display.height = (<p2.Circle>circleShape).radius * 2
    }
        this.display.anchorOffsetX = this.display.width / 2
        this.display.anchorOffsetY = this.display.height / 2;
        this.display.x = -100;
        this.display.y = -100;
        this.display.rotation = 270
        this.shpeBody.displays = [this.display];
        this.addChild(this.display);   
}[/mw_shl_code]
上述代码中先创建Box或者Circle形状,并通过addShape()函数,将其添加到刚体body中,最后通过world的addBody()将刚体添加到世界中,完成一个P2物理应用创建。注意:Egret中加载进来的图像,其原点默认为左上角,而P2中刚体的原点处于其中心位置,如下图(盗了一张图)
所以需要根据刚体重心坐标偏移量(offsetX,offsetY)设置图像的anchorOffsetX ,anchorOffsetY 属性。
4.帧函数实时调用step()函数
[mw_shl_code=applescript,true]//帧事件,步函数
private update() {
    this.world.step(2.5);
    var l = this.world.bodies.length;
    for (var i:number = 0; i < l; i++) {
        var boxBody:p2.Body = this.world.bodies;
        var box:egret.DisplayObject = boxBody.displays[0];
        if (box) {
            //将刚体的坐标和角度赋值给显示对象
            box.x = boxBody.position[0];
            box.y = boxBody.position[1];
            box.rotation = boxBody.angle * 180 / Math.PI;
            //如果刚体当前状态为睡眠状态,将图片alpha设为0.5,否则为1
            if (boxBody.sleepState == p2.Body.SLEEPING) {
                box.alpha = 0.5;
            }
            else {
                box.alpha = 1;
            }
        }
    }
}[/mw_shl_code]
world中所有的刚体都保存在属性bodies数组中,通过数组的foreach()方法,可以遍历其中的每一个body,然后拿到body的显示对象,再将刚体的坐标和角度属性赋值给显示对象,实时更新即可。
5.在createGameScene()中依次调用
[mw_shl_code=applescript,true]protected createGameScene(): void {
    let img:egret.Bitmap = new egret.Bitmap();
    img = this.createBitmapByName("bg_jpg");
    img.width = this.stage.stageWidth;
    img.height = this.stage.stageHeight;
    this.addChild(img);
    this.CreateWorld();
    this.CreatePlane();
   
    this.addEventListener(egret.Event.ENTER_FRAME,this.update,this);
    this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.onButtonClick,this);
}[/mw_shl_code]结论
本教程所涉及的内容,只是对P2物理引擎的初级了解和使用。然而物理引擎需要我们学习的知识还有很多,还有更强大更好玩的功能等待我们去探索!
附上GitHub源码地址
新手教程1】4天完成一款小游戏 http://bbs.egret.com/thread-49996-1-1.html
【新手教程2】EUI卡牌游戏的制作 http://bbs.egret.com/forum.php?m ... =1&extra=#pid301469
【新手教程3】微信小游戏排行榜 http://bbs.egret.com/thread-50903-1-1.html
【新手教程4】微信小游戏转发 http://bbs.egret.com/thread-50904-1-1.html
【新手教程5】Egret搭建WebSocket简易聊天室http://bbs.egret.com/forum.php?m ... B%E6%95%99%E7%A8%8B
【新手教程7】密室逃脱Egret游戏教程http://bbs.egret.com/forum.php?m ... B%E6%95%99%E7%A8%8B
【新手教程8】DragonBones的使用http://bbs.egret.com/forum.php?m ... B%E6%95%99%E7%A8%8B

分享到 :
2 人收藏

15 个回复

倒序浏览
大西几  圆转纯熟 | 2018-10-8 14:21:20
新鲜出炉的 我大番薯来看一看
ccrubby  圆转纯熟 | 2018-10-15 22:07:51
不知道是不是引擎版本问题,我的引擎是5.2.4的,在引入p2物理库时按照本文目录结构和模块字段添加方式(将physics模块放入modules目录下并添加{  "name":"physics",  "path":"../physics"}后)一直会提示无法找到相应的模块,还会把libs目录下的modules目录删除;只有将physics模块放入libs目录下而不是modules目录下并且路径为./libs/physics后才能编译通过。而我的方法与http://developer.egret.com/cn/gi ... ructions/index.html此文档中的是一致的。
熊猫少女  圆转纯熟 | 2018-10-16 09:25:21
ccrubby 发表于 2018-10-15 22:07
不知道是不是引擎版本问题,我的引擎是5.2.4的,在引入p2物理库时按照本文目录结构和模块字段添加方式(将p ...

引擎版本对应库的版本,不一致不行的
835548738  初窥堂奥 | 2018-10-19 19:32:41
现在能跑了

P2_New.rar

970.68 KB, 下载次数: 64, 下载积分: 银子 -1

超超超  自成一派 | 2018-10-19 20:36:09
要是能把那位大神做的Air Monkey Physics Editor继续优化下去就好了,虽然这个编辑器现在有点坑,但觉着还是挺好用的
kinoko  登堂入室 | 2018-11-6 15:46:36
熊猫少女 发表于 2018-10-16 09:25
引擎版本对应库的版本,不一致不行的

引擎版本对应的库怎么看呢
熊猫少女  圆转纯熟 | 2018-11-6 19:19:59
kinoko 发表于 2018-11-6 15:46
引擎版本对应的库怎么看呢

github上看的出来啊
Kirito...  登堂入室 | 2018-11-28 13:09:06
太感谢啦,对于我这样的新手来说很有用。
静静icon  官方团队 | 2018-11-28 16:48:08
666
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|京网文[2014]0791-191号|京ICP证150115号|Egret社区 ( 京ICP备14025619号 )

Powered by Discuz! X3.4 © 2001-2019 Comsenz Inc.

返回顶部