简体   繁体   English

使用 JavaScript 创建重力

[英]Create gravity using JavaScript

I am developing a physical sandbox.我正在开发一个物理沙箱。 Each body has own properties like mass, velocity and acceleration.每个物体都有自己的属性,如质量、速度和加速度。 By default all bodies fall to the ground, but some of the them have gravitation field that can attract another bodies.默认情况下,所有物体都会落到地上,但其中一些物体具有可以吸引其他物体的引力场。 I tried to calculate body's moving vectors and sum them, but it doesn't work.我试图计算身体的移动向量并将它们相加,但它不起作用。 How can this attraction be correctly implemented?如何正确实施这个吸引力?

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. As comments already pointed, you should calculate acceleration for all particles first, then move them.正如评论已经指出的那样,您应该首先计算所有粒子的加速度,然后移动它们。

  2. You are adding force to acceleration.你正在为加速增加力量。

  3. You are calculating only amount of force, not it's direction.您只计算力的大小,而不是方向。 Here is correct (i think) version:这是正确的(我认为)版本:

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

so cool.非常酷。 program is very difficult.程序非常困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM