书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
4.5 由系统组成的系统
示例代码4-4 由系统组成的系统
ArrayList<ParticleSystem> systems;
void setup() {
size(640,360);
systems = new ArrayList<ParticleSystem>();
}
void draw() {
background(255);
for (ParticleSystem ps: systems) {
ps.run();
ps.addParticle();
}
fill(0);
text("click mouse to add particle systems",10,height-30);
}
void mousePressed() {
systems.add(new ParticleSystem(1,new PVector(mouseX,mouseY)));
}
一旦鼠标被点击,一个新的粒子系统对象将会被创建并放入ArrayList中.
ParticleSystem .pde
class ParticleSystem {
ArrayList<Particle> particles; // An arraylist for all the particles
PVector origin; // An origin point for where particles are birthed
ParticleSystem(int num, PVector v) {
particles = new ArrayList<Particle>(); // Initialize the arraylist
origin = v.get(); // Store the origin point
for (int i = 0; i < num; i++) {
particles.add(new Particle(origin)); // Add "num" amount of particles to the arraylist
}
}
void run() {
for (int i = particles.size()-1; i >= 0; i--) {
Particle p = particles.get(i);
p.run();
if (p.isDead()) {
particles.remove(i);
}
}
}
void addParticle() {
particles.add(new Particle(origin));
}
// A method to test if the particle system still has particles
boolean dead() {
if (particles.isEmpty()) {
return true;
}
else {
return false;
}
}
}