build ribbons

erik natzkeのflash on the beachの発表なのかな。jonathan harrisへのレスポンスと一緒に上げられてた気がするけど。
Untitled Document
Flash on the Beach and “The Jonathan Harris Affair” | THOMAS KRÄFTNER

これのParticlesのソース見て、動かしてみて、この書き方がいいのかどうかは知らないけどprocessingでもループ内でnewしてParticlesを生み出したいと思った。最初に思いついたのが配列を使って実現する方法。サイズの宣言と値を代入する必要があるので、適当に埋めてやってたんだけど、ださい(し、これでは意味がない。最初に決まった数のオブジェクトを作るんじゃなくて、ループの度に増やしたい)。

とりあえずParticleクラス
Particle.pde

class Particle {
  float x;
  float y;
  float vx;
  float vy;
  float rad;
  
  Particle(float x, float y, float vx, float vy, float rad) {
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.rad = rad;
  }
  void draw() {
    x += vx;
    y += vy;
    ellipse(x, y, rad, rad);
  }
}

実行するメインのコード。
particleTest1.pde

Particle[] p = new Particle[500];
int idx = 0;
float rad = 10;
void setup() {
  size(800, 400);
  fill(0);
  smooth();
  for(int i=0;i<p.length;i++) {
    p[i] = new Particle(0,0,0,0,0);
  }
}

void draw() {
  background(255);
  spawnParticles();
  drawParticles();
}

void spawnParticles() {
  if(idx>p.length-1) {
    idx = 0;
  }
  float vx = random(-1, 1);
  float vy = random(-1, 1);
  p[idx] = new Particle(mouseX, mouseY, vx, vy, rad);
  idx++;
}

void drawParticles() {
  for(int i=0;i<p.length;i++) {
    p[i].draw();
  }
}

actionscript3の場合は描画されるオブジェクトはディスプレイリストで管理されるから、addChildでひたすらオブジェクトを追加しつつ増え過ぎたら削除、みたいな書き方ができる。
processingでもそんな方法はないのかなと思ったらサンプルにあった。
ArrayListClass \ Learning \ Processing 1.0 (BETA)

これはBallクラスにlifeプロパティをもたせてあり、255回ループで呼ばれたらfinished()メソッドがtrueを返して、ballsから削除されるようになってる。

(Example>Topics>Simulate>MultipleParticleSystemsとかもいい。nature of codeでやったVector3DクラスがPVectorクラスとして組み込まれてる。各メソッドについてもサンプルがついてて親切。)

for (int i = balls.size()-1; i >= 0; i--) { 

は毎回balls.size()を参照しなくてもいいようにするかっこいい書き方。

というのを参考にしつつ、一定数超えたら削除していく方法で書き直したのがこれ。前出のParticleクラスはそのまま使える。
ArrayList使った思い通りの方法。
particleTest1_2.pde

ArrayList particles;
float rad = 10;
void setup() {
  size(800, 400);
  fill(0);
  smooth();
  particles = new ArrayList();
}

void draw() {
  background(255);
  spawnParticles();
  drawParticles();
}

void spawnParticles() {
  float vx = random(-1, 1);
  float vy = random(-1, 1);
  particles.add(new Particle(mouseX, mouseY, vx, vy, rad));
  if (particles.size()>500) {
    particles.remove(0);
  }
}

void drawParticles() {
  for(int i=particles.size()-1; i >= 0; i--) {
    Particle p = (Particle)particles.get(i);
    p.draw();
  }
}

(11/7修正)重力のための変数gravityを削除。まだ関係ないので。