第二个小实验的实现效果如下:
//主函数
Mover[] movers = new Mover[12];
void setup() {
size(640,360);
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].display();
}
}
//被引用的Mover类
//Mover类
class Mover {
PVector position;
PVector velocity;
PVector acceleration;
float topspeed;
Mover() {
position = new PVector(random(width),random(height));
velocity = new PVector(0,0);
topspeed = 6;
}
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);
if ((position.x > width-48) || (position.x < 48)) {
velocity.x = velocity.x * -1;
}
if ((position.y > height-48) || (position.y < 48)) {
velocity.y = velocity.y * -1;
}//边缘显示检测
}
void display() {
//设置颜色
float b = randomGaussian();
float sd = 100; float mean = 100;
b = constrain((b * sd) + mean,190,255);
float r = randomGaussian();
r = constrain((r * sd) + mean,100,255);
rectMode(CENTER);
stroke(255);
strokeWeight(2);
fill(r,20,b);
ellipse(position.x,position.y,48,48);
stroke(123,150,255);
strokeWeight(3);
line(width/2, height/2, position.x,position.y);
stroke(123,150,255,230);
strokeWeight(1);
line(0,0, position.x,position.y);
line(0,height, position.x,position.y);
line(width,0, position.x,position.y);
line(width,height, position.x,position.y);
/*网格线*/
stroke(123,150,255);
fill(123,150,255);
rect(0,0,48,48); rect(0,height,48,48); rect(width,0,48,48);
rect(width,height,48,48);
}
}