今天分享的内容是:基于Egret使用P2物理引擎实现物理小球示例效果。

了解更多信息,您可以查看P2物理引擎GitHub地址或者是EgretP2物理系统文档。

* 第三方库的引入
* 创建一个P2物理项目

一、第三方库的引入

1.首先新建一个项目。

2.在GitHub上下载包括P2物理引擎库的完整第三方库,解压后按照路径找到physics模块。

3.将physics模块放到新建项目根目录的同级目录。

4.修改egretProperties.json,modules数组里增加

{ "name":"physics", "path":"../physics" }

5.然后找到插件-Egret项目工具-编译引擎编译一下就成功引入P2库,如下图。

二、创建一个P2物理项目

使用P2物理引擎创建物理应用的过程大致分为5个步骤:

1.创建world世界 2.创建shape形状 3.创建body刚体 4.实时调用step()函数,更新物理模拟计算 5.基于形状、刚体,使用Egret渲染,显示物理模拟效果

**下面根据这5个步骤进行代码构建。

1.打开Main.ts,首先创建world世界**

//创建Word世界
private world:p2.World;
private CreateWorld(){
    this.world = new p2.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

//生成地板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);
}

Plane相当于地面,默认面向Y轴方向。 因为这个Y轴是P2的Y轴,而不是Egret的Y轴。P2和Egret的Y轴是相反的。所以将地面翻转180度。 planeBody.angle = Math.PI

3.点击创建足球或者矩形方块

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);    
}

上述代码中先创建Box或者Circle形状,并通过addShape()函数,将其添加到刚体body中,最后通过world的addBody()将刚体添加到世界中,完成一个P2物理应用创建。 注意:Egret中加载进来的图像,其原点默认为左上角,而P2中刚体的原点处于其中心位置,如下图(盗了一张图)

所以需要根据刚体重心坐标偏移量(offsetX,offsetY)设置图像的anchorOffsetX ,anchorOffsetY 属性。

**4.帧函数实时调用step()函数 **

//帧事件,步函数
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[i];
        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;
            }
        }
    }
}

world中所有的刚体都保存在属性bodies数组中,通过数组的foreach()方法,可以遍历其中的每一个body,然后拿到body的显示对象,再将刚体的坐标和角度属性赋值给显示对象,实时更新即可。

5.在createGameScene()中依次调用

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);
}

本教程所涉及的内容,只是对P2物理引擎的初级了解和使用。然而物理引擎需要我们学习的知识还有很多,还有更强大更好玩的功能等待我们去探索!

附上GitHub源码地址:https://github.com/duan003387...