xxxxxxxxxx
112
let particles = [];
let lifeSpanMin = 50;
let lifeSpanMax = 100;
let maxVel = 3;
let repChance = 0.01;
let viewButton;
let toggleViewGate = true;
function createParticles(posX,posY){
for(let i = random(1,5); i >= 0; i--){
particles.push(new Particle(posX,posY));
}
}
function mouseDragged(){
createParticles(mouseX,mouseY);
}
function setup() {
createCanvas(windowWidth, windowHeight);
viewButton = createButton('Toggle View');
viewButton.position(10, height+20);
viewButton.mousePressed(function toggle(){toggleViewGate = !toggleViewGate;});
}
function draw() {
background(220);
for(let i = particles.length - 1; i >= 0; i--){
let p = particles[i];
if(p.alive){
p.repoduce();
p.update();
p.findNeighbors(particles);
p.show();
}else{
particles.splice(i,1);
}
}
}
class Particle{
constructor(posX,posY){
this.pos = createVector(posX,posY);
this.vel = createVector(random(-maxVel,maxVel),random(-maxVel,maxVel));
this.acc = createVector();
this.lifeMax = random(lifeSpanMin,lifeSpanMax);
this.lifeSpan = 0;
this.alive = true;
this.neighbors = [];
this.hue = createVector(0,0,0);
}
repoduce(){
if(random(1) < repChance && this.lifeSpan > this.lifeMax/2){
createParticles(this.pos.x,this.pos.y);
}
}
findNeighbors(particles){
this.neighbors = [];
let range = map (this.lifeMax,lifeSpanMin,lifeSpanMax,10,50);
for(let p of particles){
if(p != this && !p.neighbors.includes(this)){
let d = this.pos.dist(p.pos);
if(d < range){
this.neighbors.push(p);
}
}
}
}
update(){
if(this.lifeSpan <= this.lifeMax){
this.lifeSpan ++;
}else{
this.alive = false;
}
//this.vel.add(this.acc);
this.vel.mult(0.95);
this.pos.add(this.vel);
//this.acc.mult(0);
}
show(){
this.hue.x = map(this.lifeSpan, 0, this.lifeMax, 21,35);
this.hue.y = map(this.lifeSpan, 0, this.lifeMax, 34, 57);
this.hue.z = map(this.lifeSpan, 0, this.lifeMax, 56, 93);
let alpha = map(this.lifeSpan, 0, this.lifeMax, 50, 1);
stroke(this.hue.x,this.hue.y,this.hue.z,alpha);
point(this.pos.x,this.pos.y);
if(toggleViewGate){
noFill();
for(let n of this.neighbors){
line(this.pos.x,this.pos.y,n.pos.x,n.pos.y);
}
}else{
noStroke();
fill(this.hue.x,this.hue.y,this.hue.z,alpha);
beginShape();
vertex(this.pos.x,this.pos.y);
for(let n of this.neighbors){
vertex(n.pos.x,n.pos.y);
}
vertex(this.pos.x,this.pos.y);
endShape();
}
}
}