「The Nature of Code」から複数のパーティクルとイテレータについて取り上げます。複数のパーティクルをイテレータで処理する方法を見ていきます。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。
複数のパーティクルとイテレータ
複数のパーティクルをイテレータを使って処理します。
//ArrayList of particles with Iterator import java.util.Iterator; ArrayList<Particle> particles; void setup(){ size(200, 200); particles = new ArrayList<Particle>(); } void draw(){ background(255); particles.add(new Particle(new PVector(width/2, 50))); Iterator<Particle> it = particles.iterator(); while(it.hasNext()){ Particle p = it.next(); p.run(); if(p.isDead()){ it.remove(); println("Particle dead!"); } } }
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の勉強にもなるので一石二鳥です。