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

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

 メニュー

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

Proccesing:パーティクルと力

「The Nature of Code」からパーティクルと力について取り上げます。パーティクルに力を適用します。ここでは、重力を付加します。Processingでプログラムを書いて、動作を確認します。動作を確認できるところがProcessingの楽しいところです。

パーティクルと力

以下は、パーティクルに重力を付加する参考例です。

//Particle system with forces
ParticleSystem ps;

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

void draw(){
  background(255);
  
  //重力
  PVector gravity = new PVector(0, 0.1);
  ps.applyForce(gravity);  
  
  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 applyForce(PVector f){
    for(Particle p : particles){
      p.applyForce(f);
    }
  }
  
  //実行
  void run(){
    Iterator<Particle> it = particles.iterator();
    while(it.hasNext()){
      Particle p = it.next();
      p.run();
      if(p.isDead()){
        it.remove();
      }
    }
  }
}
class Particle{
  PVector location;
  PVector velocity;
  PVector acceleration;
  float lifespan;
  
  float mass = 1;
  
  //コンストラクタ
  Particle(PVector l){
    location = l.copy();
    velocity = new PVector(random(-1, 1), random(-2, 0));
    acceleration = new PVector(0, 0);
    lifespan = 255.0;
  }
  
  //実行
  void run(){
    update();
    display();
  }
  
  //力の適用
  void applyForce(PVector force){
    PVector f = force.copy();
    f.div(mass);
    acceleration.add(f);
  }
  
  //座標の更新
  void update(){
    velocity.add(acceleration);
    location.add(velocity);
    acceleration.mult(0);
    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;
    }
  } 
}

まとめ

「The Nature of Code」からパーティクルと力について取り上げました。パーティクルに力を適用しました。引き続き、「The Nature of Code」の内容を勉強します。

参考書籍

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

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