单个粒子

2022-05-07  本文已影响0人  大龙10

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

4.2 单个粒子

  

1、单个粒子类

class Particle {
    PVector location;   Particle对象是Mover对象的别名,它有位置、速度和加速度
    PVector velocity;
    PVector acceleration;
Particle(PVector l) {
    location = l.get();
    acceleration = new PVector();
    velocity = new PVector();
}
void update() {
    velocity.add(acceleration);
    location.add(velocity);
}
void display() {
    stroke(0);
    fill(175);
    ellipse(location.x,location.y,8,8);
}
}

2、生存期

这是一个很简单的粒子,我们可以继续完善这个粒子类:

  典型的粒子系统中都有一个发射器,发射器是粒子的源头,它控制粒子的初始属性,包括位置、速度等。

  加入生存期后的粒子类如下所示:

class Particle {
    PVector location;
    PVector velocity;
    PVector acceleration;
    float lifespan;   该变量用于管理粒子的“生存”时长
Particle(PVector l) {
    location = l.get();
    acceleration = new PVector();
    velocity = new PVector();
    lifespan = 255;  为了便于实现,我们从255开始递减 
  }
void update() {
    velocity.add(acceleration);
    location.add(velocity);
    lifespan -= 2.0;  递减生存期变量
  }
void display() {
    stroke(0, lifespan);  由于生存期的范围是255~0,我们可以把它当成alpha值
    fill(175,lifespan);
    ellipse(location.x,location.y,8,8);
  }
}

  为了便利,我们让生存期从255开始递减,直至减到0。因为我们让粒子的alpha透明度等于生存期,所以当粒子“消亡”时,会变得完全透明,这样它在屏幕中也就不可见了。

3、检查粒子函数

4、示例

  在创建多个粒子对象之前,应该确保粒子类能够正常工作,我们可以用Sketch模拟单个粒子对象的运动情况。
  模拟代码如下所示,在其中加入了两个额外功能:

示例代码4-1 单个粒子

Particle p;

void setup() {
  size(640,360);
  p = new Particle(new PVector(width/2,20));
  background(255);
  smooth();
}

void draw() {
  background(255);
  
  p.run();
  if (p.isDead()) {
    p = new Particle(new PVector(width/2,20));
    //println("Particle dead!"); 
  }
}

Particle.pde

class Particle {
  PVector position;
  PVector velocity;
  PVector acceleration;
  float lifespan;

  Particle(PVector l) {
    acceleration = new PVector(0, 0.05);
    velocity = new PVector(random(-1, 1), random(-1, 0));
    position = l.get();
    lifespan = 255.0;
  }

  void run() {
    update();
    display();
  }

  // Method to update position
  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifespan -= 2.0;
  }

  // Method to display
  void display() {
    stroke(0, lifespan);
    strokeWeight(2);
    fill(127, lifespan);
    ellipse(position.x, position.y, 12, 12);
  }

  // Is the particle still useful?
  boolean isDead() {
    if (lifespan < 0.0) {
      return true;
    } 
    else {
      return false;
    }
  }
}

5、运行结果

上一篇 下一篇

猜你喜欢

热点阅读