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);
// console.log (particles)
}
}
// console.log(createParticles())
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),
}
}
/*
while (compareParticles < length of particles)
DO let compare_particle = 0
for (let i=1, i<length of particles, i++)
if distance (particles[compare particles], particles[i]) < 100
draw line
compare particles ++
*/
function drawConnectionsBetweenNearbyParticles() {
let compareParticle = 0;
while (compareParticle < particles.length) {
let x1 = particles[compareParticle].position.x
let y1 = particles[compareParticle].position.y
for (let i = 1; i < particles.length; i++) {
let x2 = particles[i].position.x
let y2 = particles[i].position.y
if (dist(x1, y1, x2, y2) < 100) {
stroke("white");
line(x1, y1, x2, y2);
}
// console.log(compareParticle)
// console.log(Object.keys(particles.position.x).length)
}
compareParticle++
}
}
/*take first two particles, and draw line between positions*/
// draw a red circle, 50 pixels in diameter, at the position of the very first particle in the array
// particles.position[0]
// TODO: YOU need to implement this function!
// const pos1 = particles[0].position
// const pos2 = particles[1].position
// stroke("white")
// line(pos1.x, pos1.y, pos2.x, pos2.y)