书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第8章目录
8.5 树
本节要模拟的是带有分支的树。
首先,让我们用确定性分形技术构建一棵分形树。构建规则如下:
再一次,我们用递归方式构建了一个分形:树枝是一个线段,线段末尾有两根小树枝。
translate(0,-100);
rotate(PI/6);
line(0,0,0,-100);
translate(width/2, height);
line(0,0,0,-100); 树干
translate(0,-100);
pushMatrix();
rotate(PI/6);
line(0,0,0,-100); 右边的树枝
popMatrix();
rotate(-PI/6);
line(0,0,0,-100); 左边的树枝
void branch() {
line(0, 0, 0, -100); 绘制树枝
translate(0, -100); 平移到末尾
pushMatrix();
rotate(PI/6); 向右旋转,再画新的树枝
branch();
popMatrix();
pushMatrix();
rotate(-PI/6); 向左旋转,再画新的树枝
branch();
popMatrix();
}
void branch(float len) { branch()函数接受一个长度参数
line(0, 0, 0, -len);
translate(0, -len);
len *= 0.66; 每个树枝的长度以2/3的倍数缩短
if (len > 2) {
pushMatrix();
rotate(theta);
branch(len); 后续的branch()调用必须传入长度参数
popMatrix()
pushMatrix();
rotate(-theta);
branch(len);
popMatrix();
}
}
void branch(float len) {
float theta = random(0, PI/3); 选择一个随机数作为树枝的角度
line(0, 0, 0, -len);
translate(0, -len);
len *= 0.66;
if (len > 2) {
pushMatrix();
rotate(theta);
branch(len);
popMatrix();
pushMatrix();
rotate(-theta);
branch(len);
popMatrix();
}
}