书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
4.4 粒子系统类
到目前为止,我们已经做了两件事情:
ParticleSystem.pde
class ParticleSystem {
ArrayList<Particle> particles;
PVector origin; // 这个粒子系统包含一个原点
ParticleSystem(PVector position) {
origin = position.get();
particles = new ArrayList<Particle>();
}
void addParticle() {
particles.add(new Particle(origin));
}
void run() {
for (int i = particles.size()-1; i >= 0; i--) {
Particle p = particles.get(i);
p.run();
if (p.isDead()) {
particles.remove(i);
}
}
}
}
示例代码4-3 单个粒子系统
ParticleSystem ps;
void setup() {
size(640,360);
ps = new ParticleSystem(new PVector(width/2,50));
}
void draw() {
background(255);
ps.addParticle();
ps.run();
}
Particle.pde
class Particle {
PVector position;
PVector velocity;
PVector acceleration;
float lifespan;
color c;
Particle(PVector l) {
acceleration = new PVector(0,0.05);
velocity = new PVector(random(-1,1),random(-2,0));
position = l.get();
lifespan = 255.0;
c = color(random(255),random(255),random(255));
}
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(c,lifespan);
ellipse(position.x,position.y,12,12);
}
// Is the particle still useful?
boolean isDead() {
if (lifespan < 0.0) {
return true;
} else {
return false;
}
}
}