Francis89074/javascriptDemo
1
1let particles = [];2const numParticles = 25;3let cylinderRadius = 200;4let cylinderHeight = 400;5let sphereRadius = 300;6let rotationAngle = 0;7let zoom = 1;8let zoomDirection = 1;9 10function setup() {11 createCanvas(800, 800, WEBGL);12 colorMode(HSB, 360, 100, 100);13 14 for (let i = 0; i < numParticles; i++) {15 particles.push(new Particle(16 random(-cylinderRadius, cylinderRadius),17 random(-cylinderHeight/2, cylinderHeight/2),18 random(-cylinderRadius, cylinderRadius),19 i * (360/numParticles)20 ));21 }22}23 24function draw() {25 background(0);26 scale(zoom);27 28 zoom += 0.002 * zoomDirection;29 if (zoom > 1.5) zoomDirection = -1;30 if (zoom < 0.8) zoomDirection = 1;31 32 rotateY(rotationAngle);33 rotationAngle += 0.005;34 35 push();36 noFill();37 stroke(200, 50, 50, 50);38 sphere(sphereRadius);39 pop();40 41 push();42 noFill();43 stroke(100, 50, 50, 50);44 cylinder(cylinderRadius, cylinderHeight);45 pop();46 47 for (let particle of particles) {48 particle.update();49 particle.checkCollisions();50 particle.display();51 }52}53 54class Particle {55 constructor(x, y, z, hue) {56 this.pos = createVector(x, y, z);57 this.vel = p5.Vector.random3D().mult(random(2, 5));58 this.radius = 8;59 this.hue = hue;60 this.trail = [];61 this.maxTrailLength = 20;62 }63 64 update() {65 this.pos.add(this.vel);66 this.trail.push(this.pos.copy());67 if (this.trail.length > this.maxTrailLength) {68 this.trail.splice(0, 1);69 }70 }71 72 checkCollisions() {73 let radialDist = sqrt(this.pos.x * this.pos.x + this.pos.z * this.pos.z);74 if (radialDist + this.radius > cylinderRadius) {75 let normal = createVector(this.pos.x, 0, this.pos.z).normalize();76 let dotProduct = this.vel.dot(normal);77 this.vel.sub(normal.mult(2 * dotProduct));78 this.pos.set(79 this.pos.x * (cylinderRadius - this.radius) / radialDist,80 this.pos.y,81 this.pos.z * (cylinderRadius - this.radius) / radialDist82 );83 }84 85 if (this.pos.y + this.radius > cylinderHeight/2) {86 this.vel.y = -abs(this.vel.y);87 this.pos.y = cylinderHeight/2 - this.radius;88 }89 if (this.pos.y - this.radius < -cylinderHeight/2) {90 this.vel.y = abs(this.vel.y);91 this.pos.y = -cylinderHeight/2 + this.radius;92 }93 94 let distFromCenter = this.pos.mag();95 if (distFromCenter + this.radius > sphereRadius) {96 let normal = this.pos.copy().normalize();97 let dotProduct = this.vel.dot(normal);98 this.vel.sub(normal.mult(2 * dotProduct));99 this.pos.setMag(sphereRadius - this.radius);100 }101 }102 103 display() {104 push();105 noFill();106 strokeWeight(2);107 beginShape();108 for (let i = 0; i < this.trail.length; i++) {109 let alpha = map(i, 0, this.trail.length, 0, 100);110 stroke(this.hue, 80, 100, alpha);111 vertex(this.trail[i].x, this.trail[i].y, this.trail[i].z);112 }113 endShape();114 115 fill(this.hue, 80, 100);116 noStroke();117 translate(this.pos.x, this.pos.y, this.pos.z);118 sphere(this.radius);119 pop();120 }121}122 