「The Nature of Code」からパーティクル群をリスト化する方法を取り上げます。複数のパーティクル群を扱えるようになります。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。
パーティクル群のリスト化
前回の記事でパーティクル群を扱うクラスを作成しました。今回は、そのパーティクル群をリストとして扱うようにします。ArrayListを使い複数のパーティクル群を生成します。
//A System of Systems ArrayList<ParticleSystem> systems; void setup(){ size(200, 200); 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-10); } //クリックしたら、その場所にパーティクル群を生成 void mousePressed(){ systems.add(new ParticleSystem(1, new PVector(mouseX, mouseY))); }
import java.util.Iterator; class ParticleSystem{ ArrayList<Particle> particles; PVector origin; //各パーティクルの原点 //コンストラクタ ParticleSystem(int num, PVector v){ origin = v.copy(); particles = new ArrayList<Particle>(); //ArrayListにパーティクル群を1つ追加する for(int i = 0; i < num; i++){ particles.add(new Particle(origin)); } } //パーティクルの追加 void addParticle(){ particles.add(new Particle(origin)); } //実行 void run(){ Iterator<Particle> it = particles.iterator(); while(it.hasNext()){ Particle p = it.next(); p.run(); if(p.isDead()){ it.remove(); //パーティクルの削除 } } } //パーティクル群の生存確認 boolean dead(){ if(particles.isEmpty()){ return true; }else{ return false; } } }
class Particle{ PVector location; PVector velocity; PVector acceleration; float lifespan; //生存期間 //コンストラクタ Particle(PVector l){ location = l.copy(); velocity = new PVector(random(-1, 1), random(-2, 0)); acceleration = new PVector(0, 0.05); lifespan = 255; } //実行 void run(){ update(); display(); } //値の更新 void update(){ velocity.add(acceleration); location.add(velocity); lifespan -= 2.0; } //図形の描画 void display(){ stroke(0, lifespan); fill(175, lifespan); ellipse(location.x, location.y, 8, 8); } //パーティクルの生存確認 boolean isDead(){ if(lifespan < 0.0){ return true; }else{ return false; } } }
まとめ
「The Nature of Code」からパーティクル群をリスト化する方法について取り上げました。複数のパーティクル群を扱えるようになりました。引き続き、「The Nature of Code」の内容を勉強します。
参考書籍
※Javaの勉強にもなるので一石二鳥です。