【问题标题】:Create gravity using JavaScript使用 JavaScript 创建重力
【发布时间】:2020-09-14 11:53:27
【问题描述】:

我正在开发一个物理沙盒。每个物体都有自己的属性,如质量、速度和加速度。默认情况下,所有物体都会落到地上,但其中一些物体具有可以吸引其他物体的引力场。我试图计算身体的移动向量并将它们相加,但它不起作用。如何正确实施这个景点?

class Body {
// Physical properties
  position = { x: 0, y: 0 }
  velocity = { x: 0, y: 0 }
  acceleration = { x: 0, y: 0 }
  mass = 1.0;
  gravity = 0.0;

// ... class constructord and etc.

  move = () => {
    if(this.checkCollision == true) return;
    this.setVelocityVector();
    this.position.y += this.velocity.y;
    this.position.x += this.velocity.x;
  }

  setVelocityVector = () => {
    // By default body falls down
    this.acceleration.y = this.mass * GRAVITY_ACCELERATION;

    // Check gravity body's attraction
    activeParticles.forEach(body => {
      if(body.gravity > 0) {
        // Calculate gravity power with Newton's formula:
        // F = G * m1 * m2 / r^2 
        var rr = (this.position.x - body.position.x) * (this.position.x - body.position.x) 
                 + (this.position.y - body.position.y) * (this.position.y - body.position.y);
        var a = body.gravity * this.mass * body.mass / rr;
        this.acceleration.x += a;
        this.acceleration.y += a;
      }
    });

    this.velocity.y += this.acceleration.y;
    this.velocity.x += this.acceleration.x;
  }
}

【问题讨论】:

  • 一方面,您不能在迭代每个物体时修改它们的坐标或速度;您需要计算新值,然后在时间步结束时将它们分配回主体。
  • 你在哪里叫秋天?
  • @EliasSoares 从渲染游戏的外部函数调用

标签: javascript math simulation game-physics gravity


【解决方案1】:
  1. 正如 cmets 已经指出的,您应该先计算所有粒子的加速度,然后再移动它们。

  2. 你正在加速加速。

  3. 您只计算力的大小,而不是方向。这是正确的(我认为)版本:

     var rr = (this.position.x - body.position.x) * (this.position.x - body.position.x) 
              + (this.position.y - body.position.y) * (this.position.y - body.position.y);
     var a = body.gravity * body.mass / rr;
     this.acceleration.x += (body.position.x - this.position.x) * a / sqrt(rr);
     this.acceleration.y += (body.position.y - this.position.y) * a / sqrt(rr);
    

【讨论】:

  • 是的,现在我明白了,但我不知道如何计算身体加速度的方向。你能给我建议吗?
  • 取vector = body.position - this.position,归一化并乘以“a”。
猜你喜欢
  • 2012-02-08
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多