0
b2GravityController.prototype.Step = function (step) {
  var i = null;
  var body1 = null;
  var p1 = null;
  var mass1 = 0;
  var j = null;
  var body2 = null;
  var p2 = null;
  var dx = 0;
  var dy = 0;
  var r2 = 0;
  var f = null;
  if (this.invSqr) {
     for (i = this.m_bodyList;
     i; i = i.nextBody) {
        body1 = i.body;
        p1 = body1.GetWorldCenter();
        mass1 = body1.GetMass();
        for (j = this.m_bodyList;
        j != i; j = j.nextBody) {
           body2 = j.body;
           p2 = body2.GetWorldCenter();
           dx = p2.x - p1.x;
           dy = p2.y - p1.y;
           r2 = dx * dx + dy * dy;
           if (r2 < Number.MIN_VALUE) continue;
           f = new b2Vec2(dx, dy);
           f.Multiply(this.G / r2 / Math.sqrt(r2) * mass1 * body2.GetMass());
           if (body1.IsAwake()) body1.ApplyForce(f, p1);
           f.Multiply((-1));
           if (body2.IsAwake()) body2.ApplyForce(f, p2);
        }
     }
  }
  else {
     for (i = this.m_bodyList;
     i; i = i.nextBody) {
        body1 = i.body;
        p1 = body1.GetWorldCenter();
        mass1 = body1.GetMass();
        for (j = this.m_bodyList;
        j != i; j = j.nextBody) {
           body2 = j.body;
           p2 = body2.GetWorldCenter();
           dx = p2.x - p1.x;
           dy = p2.y - p1.y;
           r2 = dx * dx + dy * dy;
           if (r2 < Number.MIN_VALUE) continue;
           f = new b2Vec2(dx, dy);
           f.Multiply(this.G / r2 * mass1 * body2.GetMass());
           if (body1.IsAwake()) body1.ApplyForce(f, p1);
           f.Multiply((-1));
           if (body2.IsAwake()) body2.ApplyForce(f, p2);
         }
      }
   }
}

该代码用于在 box2dweb 中模拟万有引力。为什么有两种不同的方法来计算万有引力?if 语句是做什么用的?我在互联网上看到了这个invSqr: Boolean; /// If true, gravity is proportional to r^-2, otherwise r^-1,但我不明白这个 invsqr 是什么意思。

4

1 回答 1

0

你可以看到主要的区别是这条线

if (this.invSqr) {
    ...
    f.Multiply(this.G / r2 / Math.sqrt(r2) * mass1 * body2.GetMass());
}
else {
    ...
    f.Multiply(this.G / r2 * mass1 * body2.GetMass());
}

它是为了避免sqrt在所有物理计算中进行代价高昂的后续归一化。如果不了解相关库,我无法向您解释这样做的后果。

于 2014-07-08T08:10:39.060 回答