美文网首页processing
由系统组成的系统

由系统组成的系统

作者: 大龙10 | 来源:发表于2022-05-10 06:15 被阅读0次

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

4.5 由系统组成的系统

1、由系统组成的系统

  • 我们已经知道如何实现粒子对象,
  • 也学会了如何实现粒子对象组成的系统,这个系统称为“粒子系统”,粒子系统就是由一系列独立对象组成的集合。
  • 但粒子系统本身不也是一个对象?
    如果粒子系统也是个对象,我们可以让这些粒子系统对象组成一个集合,产生一个由系统组成的系统。

2、示例

示例代码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;
    }
  }
}

3、运行结果

相关文章

网友评论

    本文标题:由系统组成的系统

    本文链接:https://www.haomeiwen.com/subject/srugyrtx.html