日常の進捗

主に自分のための,行為とその習慣化の記録

Mod:Coding Challenge #78: Simple Particle System

f:id:takawo:20171010030740g:plain

パーティクル(粒子)のシミュレーションをなるべくシンプルに記述するというもの。やってると発見がある。noiseをつかって少し揺れるようにした。グローっぽい表現を組み込むとか、もう少し改変したかったけどタイムアップ。OpenProcessingに掲載しているものはblendModeをかけてない。

ArrayList<Particle> particles;

void setup() {
  size(960, 540, P2D); 
  colorMode(HSB, 360, 100, 100, 100);
  blendMode(ADD);
  particles = new ArrayList<Particle>();
  particles.add(new Particle());
}

void draw() {
  background(0, 0, 0);
  for (Particle p : particles) {
    p.update();
    p.draw();
  }
  for (int i = 0; i < 50; i++) {
    particles.add(new Particle());
  }
  for (int i = particles.size()-1; i > 0; i--) {
    if (particles.get(i).isFinish()) {
      particles.remove(i);
    }
  }
  println(particles.size());
}

class Particle {
  PVector pos;
  PVector vel;
  float d;
  float hue;
  float alpha;
  float alphaSpan;
  float randomseed;
  Particle() {
    pos = new PVector(width/2, height-20);
    vel = new PVector(random(-1, 1), random(-5, -1));
    d = random(8, 16);
    hue = random(0, 60);
    alpha = random(50, 100);
    alphaSpan = random(0.003, 0.03) * alpha;
    randomseed = random(1, 1000);
  }
  void applyForce(PVector v) {
    vel.add(v);
  }

  void update() {
    float n = noise(randomseed*0.01, frameCount*0.01);
    n = map(n, 0, 1, -0.01, 0.01);
    applyForce(new PVector(n, 0));
    pos.add(vel);
    alpha -= alphaSpan;
    d -= 0.1;
  }

  boolean isFinish() {
    return alpha < 0;
  }

  void draw() {
    noStroke();
    fill(hue, 50, 50, alpha);
    ellipse(pos.x, pos.y, d, d);
  }
}

リファレンス