第0章 引言
这一章的关键词是“随机”。
使用random()函数:
直接使用random(最大值)即可得到一个在0~最大值之间的随机浮点数。
void setup(){
frameRate(60);
size(528,414);
}
void draw(){
//background(255);
int r = int(random(255));
int g = int(random(255));
int b = int(random(255));
int a = int(random(255));
println(r,g,b);
stroke(r,g,b,a);
line(width/2,height/2,random(width),random(height));
}
使用noise()函数
Processing的随机功能包括柏林噪声和普通的随机数。柏林噪声有广泛的使用,比如近似产生随机地形,随机云彩等。
与random()函数不同,柏林噪声是在无限的n维空间中定义的,其中每对坐标对应一个固定的半随机值(仅在程序的生命周期内固定)。结果值将始终介于0.0和1.0之间。处理可以计算一维、二维和三维噪声,具体取决于给定的坐标数目。可以通过在噪波空间中移动来设置噪波值的动画。
void setup()
{
size(600,300, P3D);
background(0);
fill(255,128);
noStroke();
lights();
}
float t =0;
void draw( )
{
++t;
clear();
for (int x = 0; x<width; x+=20)
{
for (int y = 0; y<height; y+=20)
{
for (int z = 40; z< 300; z+=20)
{
float n = noise(0.02*x, 0.02*y, 0.02*(z+t));
translate(x, y, -z);
fill(255,n*160);
box(n*25);
translate(-x, -y, z);
}
}
}
}
在noise函数的某个输入上添加与t有关的项,可以产生随时间平移的柏林噪声效果。如下图所示
第1章 向量
一个用于描述二维或三维向量,特别是欧几里德(也称为几何)向量的类。向量是具有大小和方向的实体。其数据类型存储向量的分量(x,y为2D,x,y,z为3D)。我们可以通过mag()和heading()方法访问大小和方向。
在许多Processing示例中,可以看到PVector用于描述位置,速度或加速度。例如,如果考虑在屏幕上移动一个矩形,则在任何给定的时刻,它都有一个位置(一个从原点到其位置的向量),一个速度(每个时间单位的对象位置变化的速率)作为向量)和加速度(物体的速度随时间变化的速率,表示为向量)。由于向量表示值的分组,我们不能简单地使用传统的加法/乘法等。相反,我们需要做一些“向量”数学,而PVector类中的方法使其变得容易。
Mover[] movers = new Mover[20];
void setup() {
size(200,200);
background(255);
for(int i = 0; i < movers.length; i++) {
movers[i] = new Mover();
}
}
void draw() {
background(255);
for(int i = 0; i < movers.length; i++) {
movers[i].update();
movers[i].checkEdges();
movers[i].display();
}
}
class PVector {
float x;
float y;
PVector(float x_,float y_) {
x = x_;
y = y_;
}
void add(PVector v) {
x = x + v.x;
y = y + v.y;
}
void sub(PVector v) {
x = x - v.x;
y = y - v.y;
}
void mult(float n) {
x = x * n;
y = y * n;
}
void div(float n) {
x = x / n;
y = y / n;
}
float mag() {
return sqrt(x * x + y * y);
}
void normalize() {
float m = mag();
if(m != 0) {
div(m);
}
}
void limit(float max) {
if(mag() > max) {
normalize();
mult(max);
println(mag());
}
}
}
class Mover {
PVector location;
PVector velocity;
PVector acceleration;
float topspeed;
Mover() {
location = new PVector(random(width),random(height));
velocity = new PVector(0,0);
topspeed = 4;
}
void update() {
PVector mouse = new PVector(mouseX,mouseY);
mouse.sub(location);
PVector dir = mouse;
dir.normalize();
dir.mult(0.5);
acceleration = dir;
velocity.add(acceleration