xxxxxxxxxx
74
//array to store particle objects
let particleSystem = [];
function setup() {
createCanvas(400, 400);
colorMode(HSB);
}
function draw() {
background(220);
//create a new particle object
let particle = new Particle();
//put new object into array
particleSystem.push(particle);
//for every particle in the array, draw it, move it, and check if it needs to be removed
for(let p in particleSystem){
particleSystem[p].draw();
particleSystem[p].move();
//if checkAlive function returns false, take out particle
if(!particleSystem[p].checkAlive()){
particleSystem.splice(p,1);
}
}
}
class Particle {
constructor(){
//position
this.x = random(width);
this.y = random(height);
//speed
this.vx = random(-2,2);
this.vy = random(-2,2);
//color, using HSB mode!
this.hue = random(360);
this.c = color(this.hue,100,100);
//life span
this.alive = true;
}
//displays particle on screen
draw(){
this.c = color(this.hue, 100, 100);
fill(this.c);
noStroke();
ellipse(this.x,this.y,20,20);
}
//adjusts position
move(){
this.x += this.vx;
this.y += this.vy;
// this.brightness += 0.5;
}
//checks if particle has hit edge of screen, returns true if it hasn't, returns false if it has
checkAlive(){
if(this.x > width || this.x < 0){
this.alive = false;
}
if(this.y >height || this.y <0){
this.alive = false;
}
return this.alive;
}
}