第0章 引言
通过构建walker类,创建两个walker对象,实现两个圆点的随机移动,以模仿笔墨的扩散。
代码如下:
class Walker{
int x;
int y;
Walker(){
x=width/2;
y=height/2;
}
void display(){
stroke(100,50,200);
ellipse(x,y,1,1);
}
void step()
{
int stepx=int(random(3))-1;
int stepy=int(random(3))-1;
x+=stepx;
y+=stepy;
}
}
Walker w,h;
void setup()
{
size(640,360);
w=new Walker();
h=new Walker();
background(255);
}
void draw()
{
w.step();
h.step();
w.display();
h.display();
}
第1章 向量
综合运用向量的加减法、乘除法、计算单位长度、单位化向量、速度与加速度,创建Movers【】对象数组,实现Movers集合朝着鼠标移动位置聚集。
代码如下:
class Mover {
PVector position;
PVector velocity;
PVector acceleration;
float topspeed;
Mover() {
position = new
PVector(random(width),random(height));
velocity = new PVector(0,0);
topspeed = 5;
}
void update()
{
PVector mouse = new PVector(mouseX,mouseY);
acceleration = PVector.sub(mouse,position);
acceleration.normalize();
acceleration.mult(0.2);
velocity.add(acceleration);
velocity.limit(topspeed);
position.add(velocity);
}
void display()
{
stroke(0);
strokeWeight(2);
fill(200,100,100);
ellipse(position.x,position.y,50,50);