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

 

posted @ 2018-10-22 19:56  wanhong  阅读(1359)  评论(0编辑  收藏  举报