元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

Proccesing:パーティクル群

「The Nature of Code」から複数のパーティクルの塊の扱い方について取り上げます。複数のパーティクルの集まりをひとまとまりとして扱います。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

パーティクル群

複数のパーティクルの集まりをパーティクル群とします。その塊を表すクラスを作ります。つまり、パーティクルオブジェクトをリストとして扱うクラスを作ります。クラス名は、ParticleSystemクラスとします。

//Simple Single Particle System
ParticleSystem ps;

void setup(){
  size(200, 200);
  ps = new ParticleSystem(new PVector(width/2, 50));
}

void draw(){
  background(255);
  ps.addParticle();
  ps.run();
}
import java.util.Iterator;

class ParticleSystem{
  ArrayList<Particle> particles;
  PVector origin;  //  各パーティクルの原点
  
  //コンストラクタ
  ParticleSystem(PVector location){
    origin = location.copy();
    particles = new ArrayList<Particle>();
  }
  
  //パーティクルの追加
  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();
        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の勉強にもなるので一石二鳥です。

» HTML入門のまとめはこちらです。