使用P2物理引擎製作物理小球

今天分享的內容是:基於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...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章