由体系构成的体系

源码 2024-9-8 02:18:11 41 0 来自 中国
书名:代码本色:用编程模拟天然体系
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目次
4.5 由体系构成的体系

1、由体系构成的体系


  • 我们已经知道怎样实现粒子对象,
  • 也学会了怎样实现粒子对象构成的体系,这个体系称为“粒子体系”,粒子体系就是由一系列独立对象构成的聚集。
  • 但粒子体系本身不也是一个对象?
    如果粒子体系也是个对象,我们可以让这些粒子体系对象构成一个聚集,产生一个由体系构成的体系。
2、示例

示例代码4-4 由体系构成的体系
ArrayList<articleSystem> systems;void setup() {  size(640,360);  systems = new ArrayList<articleSystem>();}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<article> 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<article>();   // 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、运行效果

您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 18:13, Processed in 0.165275 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表