xxxxxxxxxx
87
// Initialize an empty array to store particles
let particles = [];
function setup() {
// Create a canvas that takes up the full window size with 3D rendering enabled
createCanvas(windowWidth, windowHeight, WEBGL);
// Disable outlines for shapes
noStroke();
// Create 500 particles and add them to the particles array
for (let i = 0; i < 500; i++) {
particles.push(new Particle());
}
}
function draw() {
// Set the background color to black
background(0);
// Rotate the entire scene around the Y-axis based on the frame count
rotateY(frameCount * 0.01);
// Loop through each particle in the particles array
for (let p of particles) {
// Update the particle's color
p.moveColor();
// Display the particle on the canvas
p.display();
}
}
// Define the Particle class
class Particle {
constructor() {
// Initialize the particle's position with random coordinates within a 3D space
this.position = createVector(random(-200, 200), random(-200, 200), random(-200, 200));
// Set the particle's velocity as a random 3D vector with a random magnitude
this.velocity = p5.Vector.random3D().mult(random(0.5, 2));
// Set a random size for the particle
this.size = random(2, 5);
// Initialize the particle's color with random RGB values
this.color = createVector(random(180), random(225), random(255));
// Set a random color velocity to change the color over time
this.colorVelocity = createVector(random(-1, 1), random(-1, 1), random(-1, 1));
}
moveColor() {
// Update the particle's color by adding the color velocity
this.color.add(this.colorVelocity);
// Check if the color exceeds the bounds and invert the direction if it does
if (this.color.x > 180 || this.color.x < 0) {
this.colorVelocity.x *= -1;
}
if (this.color.y > 250 || this.color.y < 0) {
this.colorVelocity.y *= -1;
}
if (this.color.z > 255 || this.color.z < 0) {
this.colorVelocity.z *= -1;
}
}
display() {
// Save the current drawing state
push();
// Move the particle to its position in 3D space
translate(this.position.x, this.position.y, this.position.z);
// Set the fill color for the particle
fill(this.color.x, this.color.y, this.color.z);
// Draw the particle as a sphere with the specified size
sphere(this.size);
// Restore the previous drawing state
pop();
}
}