Создайте гравитацию, используя JavaScript - PullRequest
0 голосов
/ 27 мая 2020

Я разрабатываю физическую песочницу. У каждого тела есть свои свойства, такие как масса, скорость и ускорение. По умолчанию все тела падают на землю, но некоторые из них имеют гравитационное поле, которое может притягивать другие тела. Я пытался вычислить векторы движения тела и просуммировать их, но это не сработало. Как правильно реализовать этот аттракцион?

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

1 Ответ

0 голосов
/ 24 июня 2020
  1. Как уже указывалось в комментариях, вы должны сначала рассчитать ускорение для всех частиц, а затем переместить их.

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