p2 入門


心里一片空白,要弄個p2的demo出來。。。

先了解下p2的概念吧

P2只是一個算法庫,以剛體為對象模型,模擬並輸出物理碰撞、運動結果。這個過程通過持續調用world中的step()方法來實現

p2的單位是米,egret的單位是像素, 1米=50像素

p2的坐標系 x:從左往右,y:從下往上. (0,0)點在左上角.   egret的坐標系 x:從左往右,y:從上往下.(0,0)點在左下角.

p2剛體的默認錨點是在中間,egret顯示對象的錨點默認位於其左上角

 

鋼體 (它是一塊無限堅硬的物體。因此,在這塊物體上任何兩點之間的距離都被認為是固定的。Body(剛體)有自己的參數用來規定位置、質量和速度等,剛體的形狀是由Shape創建的形狀確定的)

形狀  (一個幾何形狀,可以是矩形、圓形等等)

約束 (constraint 是一個物理連接件,用來控制剛體的自由度.下面是一些常用的約束)

  1. 距離約束DistanceConstraint,
  2. 旋轉約束RevoluteConstraint
  3. 齒輪約束GearConstraint
  4. 坐標軸約束PrismaticConstraint
  5. 車輪約束WheelConstraint

 

創建形狀:  boxShape = new p2.Box({ width: 2, height: 1 });

創建鋼體:  boxBody = new p2.Body({ mass:1, position:[0,3],angularVelocity:1 });

給附加形狀: boxBody.addShape(boxShape);

添加鋼體到舞台: world.addBody(boxBody);

 

body.type=p2.Body.KINEMATIC. body的type屬性用於設置是哪種類型的鋼體,有些鋼體不參與碰撞,有些鋼體是不動的.

world.sleepMode = p2.World.BODY_SLEEPING;    sleepMode屬性用於鋼體休眠模式

 

下面是一些例子:

 

// 畫鋼體

world.on("addBody",function(evt){
  evt.body.setDensity(1);
});

 

創建汽車的輪子

// Constrain wheels to chassis with revolute constraints.
// Revolutes lets the connected bodies rotate around a shared point.
revoluteBack = new p2.RevoluteConstraint(chassisBody, wheelBody1, {
localPivotA: [-0.5, -0.3], // Where to hinge first wheel on the chassis
localPivotB: [0, 0],
collideConnected: false
});
revoluteFront = new p2.RevoluteConstraint(chassisBody, wheelBody2, {
localPivotA: [0.5, -0.3], // Where to hinge second wheel on the chassis
localPivotB: [0, 0], // Where the hinge is in the wheel (center)
collideConnected: false
});
world.addConstraint(revoluteBack);
world.addConstraint(revoluteFront);

// Enable the constraint motor for the back wheel. 后驅.哈哈
revoluteBack.enableMotor();
revoluteBack.setMotorSpeed(10);

 

 // 鋼體固定移動

boxBody = new p2.Body({
mass: 1,
position: [-0.3,2],
fixedRotation: true,
fixedX: true
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM