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

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

 メニュー

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

Proccesing:パーティクとポリモフィズム

「The Nature of Code」からパーティクルとポリモフィズムについて取り上げます。Javaポリモフィズムの例をパーティクルを用いて示します。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

ポリモフィズム

以下は、Javaポリモフィズムの参考例です。

addParticle()で、ParticleオブジェクトかConfettiオブジェクトのどちらかをランダムに生成します。

//Particle system inheritance and polymorphism
ParticleSystem ps;

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

void draw(){
  background(255);
  
  ps.addParticle();
  ps.run();
}
//パーティクル
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.0;
  }
  
  //実行
  void run(){
    update();
    display();
  }
  
  //座標の更新
  void update(){
    velocity.add(acceleration);
    location.add(velocity);
    lifespan -= 2.0;
  }
  //図形の描画
  void display(){
    stroke(0, lifespan);
    strokeWeight(2);
    fill(127, lifespan);
    ellipse(location.x, location.y, 12, 12);
  }
  
  //パーティクルの生存確認
  boolean isDead(){
    if(lifespan < 0.0){
      return true;
    }else{
      return false;
    }
  }  
}
class Confetti extends Particle{
  
  //コンストラクタ
  Confetti(PVector l){
    super(l);
  }
  
  //図形の描画
  void display(){
    //回転角
    float theta = map(location.x, 0, width, 0, TWO_PI*2);
    
    rectMode(CENTER);
    fill(175, lifespan);
    stroke(0, lifespan);
    strokeWeight(2);
    
    pushMatrix();
    translate(location.x, location.y);
    rotate(theta);
    rect(0, 0, 12, 12);
    popMatrix();
  }
}
import java.util.Iterator;

class ParticleSystem{
  ArrayList<Particle> particles;
  PVector origin;  //パーティクルの座標
  
  //コンストラクタ
  ParticleSystem(PVector location){
    origin = location.copy();
    particles = new ArrayList<Particle>();
  }
  
  //パーティクルの追加
  void addParticle(){
    float r = random(1);
    if(r < 0.5){
      //パーティクルの生成・追加
      particles.add(new Particle(origin));
    }else{
      //紙吹雪の生成・追加
      particles.add(new Confetti(origin));
    }
  }
  
  //実行
  void run(){
    Iterator<Particle> it = particles.iterator();
    while(it.hasNext()){
      Particle p = it.next();
      p.run();
      if(p.isDead()){
        it.remove();
      }
    }
  }
}

まとめ

「The Nature of Code」からパーティクルとポリモフィズムについて取り上げました。Javaポリモフィズムの例をパーティクルを用いて示しました。引き続き、「The Nature of Code」の内容を勉強します。

参考書籍

Javaの勉強にもなるので一石二鳥です。

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