1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
創(chuàng)建一個(gè)ArrayList
粒子,但不要在 中添加任何粒子setup()
:
ArrayList<Particle> paticles = new ArrayList<Particle>();
void setup() {
? ? size(400, 400);
? ? colorMode(HSB);
? ? stroke(255);
}
連續(xù)添加顆粒draw()
。該函數(shù)millis()
用于獲取自程序啟動(dòng)以來(lái)的時(shí)間:
void draw() {
? int num = 100;
? ? int interval = 100; // 0.5 seconds
? ? int time = millis();? ?// milliseconds? since starting the program
? ? if (paticles.size() < num && paticles.size()*interval+5000 < time) {
? ? ? ? paticles.add(new Particle(new PVector(random(width), random(height)), 100, 150));
? ? }
? ? background(0);
? ? for (int i = 0; i < paticles.size(); i ++) {
? ? ? ? Particle p = paticles.get(i);
? ? ? ? p.update(paticles, i);
? ? }
}?
請(qǐng)注意,該類(lèi)Particle必須進(jìn)行調(diào)整,因?yàn)樗仨毷褂肁rrayList可變長(zhǎng)度的數(shù)組而不是固定長(zhǎng)度的數(shù)組進(jìn)行操作:
class Particle {
? ? PVector pos;
? ? PVector vel;
? ? float r, mr;
? ? float spd = 0.1;
? ? float max = 2;
? ? Particle(PVector pos, float r, float mr) {
? ? ? ? this.pos = pos;
? ? ? ? this.r = r;
? ? ? ? this.mr = mr;
? ? ? ? vel = new PVector(random(-1, 1), random(-1, 1));
? ? }
? ? void update(ArrayList<Particle> paticles, int i) {
? ? ? ? float h = map(mouseX, 0, width, 0, 255);
? ? ? ? pos.add(vel);
? ? ? ? if (pos.x < -10) pos.x = width;
? ? ? ? if (pos.x > width + 10) pos.x = 0;
? ? ? ? if (pos.y < -10) pos.y = height;
? ? ? ? if (pos.y > height + 10) pos.y = 0;
? ? ? ? vel.x = constrain(vel.x + random(-spd, spd), -max, max);
? ? ? ? vel.y = constrain(vel.y + random(-spd, spd), -max, max);
? ? ? ? for (int j = i + 1; j < paticles.size(); j ++) {
? ? ? ? ? ? Particle pj = paticles.get(j);
? ? ? ? ? ? float ang = atan2(pos.y - pj.pos.y, pos.x - pj.pos.x);
? ? ? ? ? ? float dist = pos.dist(pj.pos);
? ? ? ? ? ? if (dist < r) {
? ? ? ? ? ? ? ? stroke(h, 255, map(dist, 0, r, 255, 0));
? ? ? ? ? ? ? ? strokeWeight(map(dist, 0, r, 3, 0));
? ? ? ? ? ? ? ? line(pos.x, pos.y, pj.pos.x, pj.pos.y);
? ? ? ? ? ? ? ? float force = map(dist, 0, r, 4, 0);
? ? ? ? ? ? ? ? vel.x += force * cos(ang);
? ? ? ? ? ? ? ? vel.y += force * sin(ang);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? float ang = atan2(pos.y - mouseY, pos.x - mouseX);
? ? ? ? float dist = pos.dist(new PVector(mouseX, mouseY));
? ? ? ? if (dist < r) {
? ? ? ? ? ? stroke(0, 0, map(dist, 0, r, 255, 0));
? ? ? ? ? ? strokeWeight(map(dist, 0, r, 3, 0));
? ? ? ? ? ? line(pos.x, pos.y, mouseX, mouseY);
? ? ? ? ? ? float force = map(dist, 0, r, 30, 0);
? ? ? ? ? ? vel.x += force * cos(ang);
? ? ? ? ? ? vel.y += force * sin(ang);
? ? ? ? }
? ? ? ? noStroke();
? ? ? ? fill(h, 255, 255);
? ? ? ? ellipse(pos.x, pos.y, 5, 5);
? ? }
}
添加回答
舉報(bào)