Perlin噪声游走
Perlin噪声介绍
Perlin噪声算法可用于生成各种自然特效,包括云层、地形和大理石的纹理。Perlin噪声算法表现出了一定的自然性,因为它能生成符合自然排序(“平滑”)的伪随机数序列。
Processing内置了Perlin噪声算法的实现:noise()函数。noise()函数可以有1~3个参数,分别代表一维、二维和三维的随机数。
随机游走
通过Perlin噪声生成x坐标和y坐标,运用到随机游走模型中。
随机游走模型代码:
class Walker{
float x,y;
int randstroke = 0;
float tx,ty;
Walker(){
//保证x和y坐标彼此独立
tx=0;
ty=1000;
}
void step(){
//一维Perlin噪声游走模型
x=map(noise(tx),0,1,0,width)*1.2;
y=map(noise(ty),0,1,0,height)*1.2;
tx+=0.01;
ty+=0.01;
}
void display(){
randomcoolColors();
line(0,y,width,y);
line(x,0,x,height);
line(0,0,x,y);
line(width,height,x,y);
line(0,height,x,y);
line(width,0,x,y);
randstroke=int(map(random(0,255),0,255,0,7));
fill(0);
ellipse(x,y,50,50);
}
void randomcoolColors(){
if (randstroke == 0){
stroke(76,random(220,255),50);//Green
}
if (randstroke == 1){
stroke(10,random(10,150),random(200,255));//Dark Blue
}
if (randstroke == 2){
stroke(255,random(150,255),40);//Gold/Yellow
}
if (randstroke == 3){
stroke(random(25),217,random(255));//Blue-Green
}
if (randstroke == 4){
stroke(255,random(90),random(233)); //hot pink
}
if (randstroke == 5){
stroke(255,random(200),2);//red-orange
}
if (randstroke == 6){
stroke(50,random(150,255),255);//Aqua-Blue
}
if (randstroke == 7){
stroke(random(20,250),10,random(230,255));//Purple
}
}
}
上述代码中在每个小球的位置画4条线,其中randomcoolColors()函数用来随机生成线条的颜色。
//perlin噪声,noise()函数实现
Walker jack[];
void setup(){
background(255,255,255);
size(640,640);
jack=new Walker[10];
for(int i=0;i<10;i++)
{
jack[i]=new Walker();
jack[i].tx = i*100;
jack[i].ty = 1000-i*100;
}
//二维噪声
loadPixels();
float xoff=0.0;
for(int x=0;x<width;x++){
float yoff=0.0;
for(int y=0;y<height;y++){
//float bright=random(255); //随机亮度
float bright=map(noise(xoff,yoff),0,1,0,255);
pixels[x+y*width]=color(bright);
yoff+=0.01;
}
xoff+=0.01;
}
updatePixels();
}
float t=0;
void draw(){
//fill(0);
//调整Perlin杂讯功能产生的特征和细节等级
noiseDetail(10,0.2);
for(int i=0;i<10;i++)
{
jack[i].step();
jack[i].display();
}
}
上述代码中,运用了二维柏林噪声来生成初始背景。
初始化了10个小球,每个小球的位置不同。
运动效果
截图效果是这样的,不知道为什么动图会变样。