LoginSignup
23
15

More than 5 years have passed since last update.

冬だけど花火がみたい??なら実装すればいい

Last updated at Posted at 2017-12-10

冬です!寒いです!

寒いから、温かい気分を味わうために花火が見たくなってきませんか?

ということで、花火を実装してしまおう!

花火の作り方

準備

Processingをインストールしてください!

Processingとはプログラマブルなベクタードローツールです。中身はJavaでできていて、文法もJavaです。

Particleクラスを作る

花火のあの火花?の部分として、Particleクラスを作りましょう。実装したい機能はこちらです。

  • 火花?が放物線を描いて動いてほしい。ようは物理法則

とりあえず、Particleクラスを作ります。

class Particle {
}

次に、物理法則が欲しいので、必要なメンバーとして、位置、速度、加速度を定義します。

class Particle {
  PVector location;
  PVector velocity;
  PVector acceleration;

  Particle (float xpos, float ypos, float xsp, float ysp) {
    this.location = new PVector(xpos, ypos); // 初期位置
    this.velocity = new PVector(xsp, ysp); // 初速
    this.acceleration = new PVector(0, 0.001); // 重力加速度的なやつ
  }
}

さて、次は物理法則に従って動かすためのメソッドです。中身は簡単です。あの有名な物理法則を定義しただけです。

$$a = \frac{dv}{dt}, v = \frac{dx}{dt} $$

class Particle {
  //...
  void update () {
    this.velocity.add(this.acceleration);
    this.location.add(this.velocity);
  }
}

そして、火花?の描画のためのメソッドを書きます。

class Particle {
  //...
  void display () {
    pushMatrix();
    resetMatrix();
    translate(this.location.x, this.location.y);
    ellipse(0, 0, 10, 10); // 円を描画
    popMatrix();
  }
}

Fireworkクラスを作る

火花?を撒き散らすクラスです。必要なのは以下の機能!

  • 火花?を360度に無作為に散らす
class Firework {
}

火花?と花火の位置をメンバーに持たせましょう。

class Firework {
  PVector location;
  ArrayList<Particle> particles;

  Firework (float xpos, float ypos) {
    this.location = new PVector(xpos, ypos);
    this.particles = new ArrayList<Particle>();
  }
}

後は、火花?を撒き散らすメソッドを書きましょう。ついでに、描画までも。

class Firework {
  //...

  // 撒き散らす
  void explode () {
    for (int i = 0; i < 400; i++) {
      float theta = random(0, TWO_PI);
      particles.add(new Particle(
        this.location.x, this.location.y, // 花火の位置に火花を設置
        cos(theta), sin(theta) // 360度のどれかに初速を設定
      ));
    }
  }

  // 火花の物理計算
  void update () {
    for (int i = 0; i < 400; i++) {
      particles.get(i).update();
    }
  }

  // 火花たちの描画
  void display () {
    fill(255); // 火花を白色にしてみた
    for (int i = 0; i < 400; i++) {
      particles.get(i).display();
    }
  }
}

さて、準備完了!

花火を打ち上げる?ために以下の用に準備!終わったら実行だ!

Firework firework;

void setup () {
  size(600, 600); // 600x600のキャンパスを作る

  firework = new Firework(width/2, height/2); // 花火をセットアップ

  firework.explode(); // 火花を撒き散らす
}

void draw () {
  background(0); // 背景はBlack
  firework.update(); 花火の計算
  firework.display(); // 花火の描画
}

え?しょぼいって?こんなの花火じゃないって?

しょうがないな〜

最後に、ちょこっと花火っぽさだすと

こうなりました!

firework.gif

最後に

これは、大学1年生のときに作ったプログラムです。二年ぐらい前かな?
大学に入ってからはじめてプログラミングに触れて、プログラミング超楽しいじゃん!って思いながらとにかくコード書いてた時期です。もちろん今も書いてますが。

ネタが思いつかなかったので、これにしてみました。

ソースコードは汚いですが、こちらになります。
https://github.com/RyosukeCla/fireworks

23
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
15