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

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

 メニュー

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

Proccesing:パーティクの回転と継承

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

継承

以下は、Javaの継承の参考例です。

Particleクラスを継承して、Confettiクラスを作ります。Confettiは紙吹雪のことで、形は四角形です。

//Particles with Inheritance
Confetti c;

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

void draw(){
  background(255);
  c.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;
  }
  
  //実行
  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);
  }
}
//紙吹雪
class Confetti extends Particle{
  
  //コンストラクタ
  Confetti(PVector l){
    super(l);
  }

  //図形の描画
  void display(){
    //回転なし
    //rectMode(CENTER);
    //fill(175, lifespan);
    //stroke(0, lifespan);
    //rect(location.x, location.y, 18, 18);
    
    //回転
    float theta = map(location.x, 0, width, 0, TWO_PI*2);
    
    rectMode(CENTER);
    fill(175, lifespan);
    stroke(0, lifespan);
    
    pushMatrix();
    translate(location.x, location.y);
    rotate(theta);
    rect(0, 0, 18, 18);
    popMatrix();
  }
}

まとめ

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

参考書籍

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

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