首页 > 代码库 > Box2D自定义重力

Box2D自定义重力

需要给刚体添加一个自定义的属性:m_customGravity,这样就可以动态的修改每一个刚体自定义的重力,查找box2d源码大约在5486行,加上红色的一句代码

 

b2Island.prototype.Solve = function (step, gravity, allowSleep) {      var i = 0;      var j = 0;      var b;      var joint;      for (i = 0;      i < this.m_bodyCount; ++i) {         b = this.m_bodies[i];         if (b.GetType() != b2Body.b2_dynamicBody) continue;         gravity = b.m_customGravity || gravity;                  b.m_linearVelocity.x += step.dt * (gravity.x + b.m_invMass * b.m_force.x);         b.m_linearVelocity.y += step.dt * (gravity.y + b.m_invMass * b.m_force.y);         b.m_angularVelocity += step.dt * b.m_invI * b.m_torque;         b.m_linearVelocity.Multiply(b2Math.Clamp(1.0 - step.dt * b.m_linearDamping, 0.0, 1.0));         b.m_angularVelocity *= b2Math.Clamp(1.0 - step.dt * b.m_angularDamping, 0.0, 1.0);      }..............代码略...........................................................................................};

 

使用的方法:

//创建一个圆形刚体
var circle = new Circle({x:mousePoint.x,y:mousePoint.y,r:20,type:sc.dynamicBody});
//给该刚体加上m_customGravity属性,并赋值垂直重力为1
circle.b2Obj.body.m_customGravity = new xengine.EasyB2D.b2Vec2(0,1);

Box2D自定义重力