「The Nature of Code」から複数のパーティクルについて取り上げます。複数のパーティクルを描画する方法を見ていきます。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。
Particleクラス
Particleクラスは、ひと粒のパーティクルのときと同じクラスを使います。
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; } } }
複数のパーティクル
複数のパーティクルを扱っていくことを考えます。配列、ArrayList、拡張for文での書き方を見ていきます。
配列
//The standard array way int total = 10; Particle[] parray = new Particle[total]; void setup(){ size(200, 200); for(int i = 0; i < parray.length; i++){ parray[i] = new Particle(new PVector(width/2, 50)); } } void draw(){ background(255); for(int i = 0; i < parray.length; i++){ Particle p = parray[i]; p.run(); if(p.isDead()){ println("Particle dead!"); } } }
ArrayList
//The new ArrayList way: int total = 10; ArrayList<Particle> plist = new ArrayList<Particle>(); void setup(){ size(200, 200); for(int i = 0; i < total; i++){ plist.add(new Particle(new PVector(width/2, 50))); } } void draw(){ background(255); for(int i = 0; i < plist.size(); i++){ Particle p = plist.get(i); p.run(); if(p.isDead()){ plist.remove(i); println("Particle dead!"); } } }
拡張for文
//The new ArrayList way: int total = 10; ArrayList<Particle> plist = new ArrayList<Particle>(); void setup(){ size(200, 200); for(int i = 0; i < total; i++){ plist.add(new Particle(new PVector(width/2, 50))); } } void draw(){ background(255); for(Particle p : plist){ p.run(); if(p.isDead()){ println("Particle dead!"); } } }
まとめ
「The Nature of Code」から複数のパーティクルについて取り上げました。複数のパーティクルを描画する方法を見てきました。引き続き、「The Nature of Code」の内容を勉強します。
参考書籍
※Javaの勉強にもなるので一石二鳥です。