xxxxxxxxxx
//See also related challenge: "Electric Particles"
//https://www.notion.so/neillzero/Electric-particles-c031ca80b88448cb9b3798b0113b4dd8
// This stores our array of particle objects
let particles = [];
// Called once at the start
function setup() {
createCanvas(windowWidth, windowHeight);
createParticles(); //create them ONCE (storing in the global array)
}
// Called 60 times per second
function draw() {
background("#303030");
moveAllParticles();
drawAllParticles();
drawConnectionsBetweenNearbyParticles();
}
function createParticles() {
const numOfParticlesToCreate = 100;
for (let i = 0; i < numOfParticlesToCreate; i++) {
const particle = {
position: randomScreenPosition(),
velocity: randomVelocity(),
size: random(2, 10),
colour: random(150, 255)
}
particles.push(particle);
}
return particles
}
function drawAllParticles() {
for (const particle of particles) {
drawOneParticle(particle);
}
}
function drawOneParticle(particle) {
fill(particle.colour);
circle(particle.position.x, particle.position.y, particle.size);
}
function moveAllParticles() {
for (const particle of particles) {
moveOneParticle(particle);
}
}
function moveOneParticle(particle) {
particle.position.x += particle.velocity.x;
particle.position.y += particle.velocity.y;
if (isOffscreen(particle.position)){
repositionParticle(particle);
}
}
function isOffscreen(position){
const {x, y} = position;
return x < 0 || x > width || y < 0 || y > height;
}
function repositionParticle(particle){
particle.position = randomScreenPosition()
}
function randomScreenPosition() {
return {
x: random(0, width),
y: random(0, height)
};
}
function randomVelocity() {
return {
x: random(-2, 2),
y: random(-2, 2),
}
}
function drawConnectionsBetweenNearbyParticles() {
createParticles();
console.log(particles);
}