ランダムな線を描く
変化が大きい線
size(500,100); background(255); strokeWeight(5); smooth(); stroke(20,50,70); line(20,50,480,50); int step = 10; float lastx = -999; float lasty = -999; float y = 50; int borderx = 20; int bordery = 10; for(int x = borderx;x <= width - borderx;x += step){ y = bordery + random(height - 2 * bordery); if(lastx > -999){ line(x,y,lastx,lasty); } lastx = x; lasty = y; }
書籍に載っていたコードですが、-999にする意味がよくわかりませんでした。
変化が少ない線
size(500,100); background(255); strokeWeight(5); smooth(); stroke(20,50,70); line(20,50,480,50); float xstep = 10; float ystep = 10; float lastx = 20; float lasty = 50; float y = 50; for(int x = 20;x <= 480;x += xstep){ ystep = random(-10,10); y += ystep; line(x,y,lastx,lasty); lastx = x; lasty = y; }
こちらのほうが自分にはしっくり来るアルゴリズムでした。
ystep = random(20) - 10;
randomの書き方は上のようにしてもOKです。
パーリンノイズ
noise関数とは
noise関数に数値を渡すと、それぞれの値によって0と1の間のノイズを返します。渡す値が毎回同じだと、同じ結果になるtので、渡す値は乱数にします。その乱数を少しずつ変化させることがポイントになります。結果、少し規則性のある乱数を生成できるようになります。
code
float ynoise = random(10); for(int x = borderx;x <= width - borderx;x += step){ y = 10 + noise(ynoise) * 80; if(lastx > -999){ line(x,y,lastx,lasty); } lastx = x; lasty = y; //ノイズ増加 ynoise += 0.1; }
コードを一部抜粋すると上のようになります。
sinに応用
size(500,100); background(255); strokeWeight(2); smooth(); stroke(20,50,70); line(20,50,480,50); int xstep = 1; float lastx = -999; float lasty = -999; float angle = 0; float y = 50; for(int x = 20;x <= 480; x += xstep){ float rad = radians(angle); y = 50 + (pow(sin(rad),3) * noise(rad*5) * 40); if(lastx > -999){ line(x,y,lastx,lasty); } lastx = x; lasty = y; angle++; }
powは累乗を計算することが出来て、第2引数の3は3乗を表しています。
乱数を自作する
float customRandom(){ float retValue = 1 - pow(random(1),0.5); return retValue; }
random(1)を1/2乗すると上のような結果になります。これはJSで実行しています。
y = 50 + (pow(sin(rad),3) * customRandom() * 40);
生成された乱数をsinの3乗に掛けてみました。心電図のようになりました。