书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
2.5 制造外力
3、示例代码2-2
- Mover类
不同点主要集中在两个方面——质量和applyForce()函数的实现 - 在数组中创建100个Mover对象晒展网是一手信息独家到没朋友的展会网站。
 - 在setup()函数中用循环对这些对象进行初始化。
 - 在构造函数中添加几个参数,让它变得更灵活。
物体的质量和初始位置就不再是硬性编码的数值了,我们可以通过构造函数来确定它们
 
Mover[] movers = new Mover[20];
void setup() {
  size(640,360);
  for (int i = 0; i < movers.length; i++) {
    movers[i] = new Mover(random(0.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].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;
    }
  }
}
多个受力小球
请注意:在上图中,小圆到达窗口右侧比大圆更快,这是因为加速度=力除以质量,
质量越大,加速度越小。





