运动101:速度和随机加速度

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

1.8 向量的运动:加速度

四、示例代码1-9

1、算法2

  • 该算法中的加速度是随机确定的,因此,我们不能只在构造函数中初始化加速度值,
  • 应该在每一轮循环中选择一个随机数作为新的加速度。
  • 我们可以在update()函数中完成这项任务。

2、随机加速度

void update() {
    acceleration = PVector.random2D();  random2D()函数返回一个长度为1、方向随机的向量 
    velocity.add(acceleration);
    velocity.limit(topspeed);
    location.add(velocity);
}

由于每次调用PVector.random2D()得到的向量都是单位向量,因此还应该改变它的大小,如下:

  • (a)将加速度乘以一个常量:
  • (b)将加速度乘以一个随机值:
acceleration = PVector.random2D();
acceleration.mult(0.5); 常量
acceleration = PVector.random2D();
acceleration.mult(random(2)); 随机

我们必须清楚地意识到这样一个关键点:加速度不仅仅会改变运动物体速度的大小,还会改变速度的方向。加速度用于操纵物体,在后面的章节中,我们将继续在屏幕上操纵物体运动,也会经常看到加速度的作用。

3、示例代码1-9

运动101(速度和随机加速度)

Mover mover;

void setup() {
  size(640,360);
  mover = new Mover(); 
}

void draw() {
 // background(255);
  mover.update();
  mover.checkEdges();
  mover.display(); 
}

//---mover.pde
class Mover {

  PVector position;
  PVector velocity;
  PVector acceleration;
  float topspeed;

  Mover() {
    position = new PVector(width/2, height/2);
    velocity = new PVector(0, 0);
    topspeed = 6;
  }

  void update() {

    acceleration = PVector.random2D();
    acceleration.mult(random(2));

    velocity.add(acceleration);
    velocity.limit(topspeed);
    position.add(velocity);
  }

  void display() {
    stroke(0);
    strokeWeight(2);
    fill(127);
    ellipse(position.x, position.y, 48, 48);
  }

  void checkEdges() {

    if (position.x > width) {
      position.x = 0;
    } 
    else if (position.x < 0) {
      position.x = width;
    }

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

推荐阅读更多精彩内容