地球引力和力的建模

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录

2.6 地球引力和力的建模

  重力和物体的质量成正比,质量越大,所受的重力也越大。因此,如果重力和质量成正比,在计算加速度时质量就会被除法抵消掉。

1、力的Sketch模拟

  • 理解力背后的原理。
  • 将力的公式分解成以下两部分。
    如何计算力的方向?
    如何计算力的大小?
  • 把力的公式实现成Processing源代码,将力的PVector对象传入Mover类的applyForce()函数。

2、示例代码2-3

重力

Mover[] movers = new Mover[20];

void setup() {
  size(640, 360);
  for (int i = 0; i < movers.length; i++) {
    movers[i] = new Mover(random(1, 4), 0, 0);
  }
}

void draw() {
  background(255);

  for (int i = 0; i < movers.length; i++) {

    PVector wind = new PVector(0.01, 0);
    PVector gravity = new PVector(0, 0.1*movers[i].mass);
   //为了让模拟更准确,我们根据质量改变重力大小

    movers[i].applyForce(wind);
    movers[i].applyForce(gravity);

    movers[i].update();
    movers[i].display();
    movers[i].checkEdges();
  }
}

mover.pde

class Mover {

  PVector position;
  PVector velocity;
  PVector acceleration;
  float mass;
  color c;
  
  Mover(float m, float x , float y) {
    mass = m;
    position = new PVector(x,y);
    velocity = new PVector(0,0);
    acceleration = new PVector(0,0);
    c = color(random(255),random(255),random(255));
  }
  
  void applyForce(PVector force) {
    PVector f = PVector.div(force,mass);
    acceleration.add(f);
  }
  
  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    acceleration.mult(0);
  }

  void display() {
    stroke(0);
    strokeWeight(2);
    //fill(0,127);
    fill(c);
    ellipse(position.x,position.y,mass*16,mass*16);
  }

  void checkEdges() {

    if (position.x > width) {
      position.x = width;
      velocity.x *= -1;
    } else if (position.x < 0) {
      velocity.x *= -1;
      position.x = 0;
    }

    if (position.y > height) {
      velocity.y *= -1;
      position.y = height;
    }

  }

}
重力与质量

尽管现在物体下落的速度相等,但质量越小的物体向右运动的加速度越大,因为风力的强度和物体的质量无关。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容