box2dweb中的这段代码是如何模拟万有引力的?为什么它使用if语句

how does this code in box2dweb simulating the universal gravitation and why does it use a if statement?

本文关键字:为什么 万有引力 语句 模拟 if 段代码 代码 何模拟 box2dweb      更新时间:2023-09-26
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是什么意思。

您可以看到主要区别是这一行

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

这是为了避免昂贵的sqrt和随后在所有物理计算中的归一化。如果不了解有问题的图书馆,我就无法向你解释这样做的后果。