xxxxxxxxxx
84
// let particles = [];// gave warning for the for loop later
const particles = []; // Creating an array to hold particles
function setup() {
createCanvas(600, 600); // setting up the canvas
no_of_Particles = width / 11; // Number of Particles
for (let i = 0; i < no_of_Particles; i++) {
particles.push(new Particle()); //pushing each new particle inside the particles array
}
}
function draw() {
background(10); // paint the background black
// for (var particle in particles){
// particle.update();
// particle.draw();
// particle.checkParticles(particles.slice(index));
// }
particles.forEach((particle, index) => {
//Javascript code for for in (python)
particle.update(); // call the particle update fucntion
particle.draw(); // call the particle draw fucntion
particle.checkParticles(particles.slice(index)); // call the check particles and what slice does is creates a copy of the particles array at that index
});
}
class Particle {
constructor() {
this.position = createVector(random(width), random(height));
this.vel = createVector(random(-2, 2), random(-2, 2));
this.size = 5;
this.color1 = color(random(255), random(255), random(50));
}
update() {
this.position.add(this.vel);
this.edges();
}
draw() {
noStroke();
fill(this.color1, random(0.3,1)) ;
circle(this.position.x, this.position.y, this.size * 3);
}
edges() {
if (this.position.x < 0 || this.position.x > width) {
this.vel.x *= -1;
}
if (this.position.y < 0 || this.position.y > height) {
this.vel.y *= -1;
}
// if(this.pos.x > width) {
// this.pos.x = 0;
// }
// if(this.pos.y > height) {
// this.pos.y = 0;
// }
}
checkParticles(particles) {
particles.forEach((particle) => {
const d = dist(
this.position.x,
this.position.y,
particle.position.x,
particle.position.y
);
if (d < 100) {
// const alpha = map(d, 0, 120, 0, 0.25);
stroke("rgba(255, 255, 255,0.5)");
line(
this.position.x,
this.position.y,
particle.position.x,
particle.position.y
);
}
});
}
}