第三个实验实现结果:
实现代码如下:
//主函数为:
Mover[] movers = new Mover[20];
Mover[] mover2s = new Mover[10];
void setup() {
size(640,360);
for (int i = 0; i < movers.length; i++) {
movers[i] = new Mover(random(0.8,6),0,0);
//mass=random(0.1,8)质量随机
}
for (int i = 0; i < mover2s.length; i++) {
mover2s[i] = new Mover(random(0.8,4),0,0);
}
}
void draw() {
background(255);
float t = 1;
for (int i = 0; i < movers.length; i++) {
//PVector wind = new PVector(noise(t)*0.1,0);
if (mousePressed) {
PVector wind = new PVector(0.01,noise(t));
movers[i].applyForce(wind);
t+=0.1;
}
PVector gravity = new PVector(0,0.1);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
for (int i = 0; i < mover2s.length; i++) {
if (mousePressed) {
PVector wind = new PVector(0.01,noise(t));
mover2s[i].applyForce(wind);
t+=0.1;
}
PVector gravity = new PVector(0,0.1);
mover2s[i].applyForce(gravity);
mover2s[i].update();
mover2s[i].display2();
mover2s[i].checkEdges2();
stroke(122,103,238,230);
strokeWeight(2);
line(width/2,0,width/2,height/2);
line(0,height/2,width/2,height/2);
}
}
//引用的Mover类
class Mover {
PVector position;
PVector velocity;
PVector acceleration;
float mass;
Mover(float m, float x , float y) {
mass = m;
position = new PVector(x,y);
velocity = new PVector(0,0);
acceleration = new PVector(0,0);
}
void applyForce(PVector force) {
PVector f = PVector.div(force,mass);
acceleration.add(f);
}
void update() {
velocity.add(acceleration);
position.add(velocity);
acceleration.mult(0);
}
void display() {
stroke(255);
strokeWeight(1);
float b = randomGaussian();
b = constrain(b,100,255);
fill(30,b,255,b);
rectMode(CENTER);
ellipse(position.x,position.y,mass*16,mass*16);
}
void display2() {
stroke(255);
strokeWeight(1);
float g = randomGaussian();
g = constrain(g,60,180);
float a = randomGaussian();
a = constrain(a,200,255);
fill(255,g,180,a);
ellipse(position.x,position.y,mass*16,mass*16);
}
void checkEdges() {
if (position.x > width) {
position.x = width;
velocity.x *= -1;
} else if (position.x < 0) {
velocity.x *= -1;
position.x = 0;
}
if (position.y > height) {
velocity.y *= -1;
position.y = height;
}
}
void checkEdges2() {
if (position.x > width/2) {
position.x = width/2;
velocity.x *= -1;
} else if (position.x < 0) {
velocity.x *= -1;
position.x = 0;
}
if (position.y > height/2) {
velocity.y *= -1;
position.y = height/2;
}
}
}