xxxxxxxxxx
89
// My fix for the Simulate Particles example
// https://github.com/markjoshua12/p5.js-website/blob/3c5c671d7d567bfee6456315c6e9168e7ff3584d/src/data/examples/en/09_Simulate/21_Particle.js
/*
* @name Particles
* @description There is a light-weight JavaScript library named
* particle.js which creates a very pleasing particle system.
* This is an attempt to recreate that particle system using p5.js.
* Inspired by Particle.js, contributed by Sagar Arora.
*/
// this class describes the properties of a single particle.
class Particle {
// setting the co-ordinates, radius and the
// speed of a particle in both the co-ordinates axes.
constructor(){
this.x = random(0,width);
this.y = random(0,height);
this.r = random(1,8);
this.xSpeed = random(-2,2);
this.ySpeed = random(-1,1.5);
}
// creation of a particle.
createParticle() {
fill(200, 169, 169, 128);
//fill('rgba(200,169,169,0.5)');
circle(this.x,this.y,this.r);
}
// setting the particle in motion.
moveParticle() {
if(this.x < 0 || this.x > width)
this.xSpeed*=-1;
if(this.y < 0 || this.y > height)
this.ySpeed*=-1;
this.x+=this.xSpeed;
this.y+=this.ySpeed;
}
// this function creates the connections(lines)
// between particles which are less than a certain distance apart
joinParticles(idx) {
for (let i = idx; i < particles.length; i++) {
let element = particles[i];
let x = this.x - element.x;
let y = this.y - element.y;
let dis = x*x + y*y;
//let dis = dist(this.x,this.y,element.x,element.y);
if(dis<85*85) {
//stroke('rgba(255,255,255,0.08)');
line(this.x,this.y,element.x,element.y);
}
}
}
}
// an array to add multiple particles
let particles = [];
let lastTime;
function setup() {
createCanvas(720, 400);
let count = 5000;//width/5;
for(let i = 0;i<count;i++){
particles.push(new Particle());
}
print("Particle Count: " + count);
lastTime = millis();
}
function draw() {
background('#0f0f0f');
for(let i = 0;i<particles.length;i++) {
noStroke();
particles[i].createParticle();
particles[i].moveParticle();
stroke(255, 255, 255, 20);
//particles[i].joinParticles(i);
}
if (millis() - lastTime > 1000) {
print("FPS: " + frameRate());
lastTime += 1000;
}
}