xxxxxxxxxx
107
// x, vx, ax -> position, velocity, acceleration on x axis
let ParticleCnt = 10; // number of particles
let particles = [];
function setup() {
let cvs = createCanvas(700, 500); // Sets default size and ratio.
cvs.canvas.style.width='100%'; // 100% width of available space
cvs.canvas.style.height='auto';
for (let i=0;i<ParticleCnt;i++) {
append(particles,new Particle());
}
}
function draw() {
background(0);
fill(120);
for (let i=0;i<particles.length;i++) {
particles[i].update();
}
fill(255);
circle(width/2,height/2,20);
}
class Particle {
constructor() {
this.size = 20;
this.vx = random(-20,20);
this.vy = random(-20,20);
this.x=this.size/2 + random(width-this.size);
this.y=this.size/2 + random(height-this.size);
}
move() {
this.x += this.vx;
this.y += this.vy;
// prevents particles from escaping the screen by
// bouncing back with reduction of velocity
if (this.x>width-this.size/2) {
this.x=width-this.size/2;
this.vx=-sqrt(this.vx);
} else if (this.x<0+this.size/2) {
this.x=this.size/2;
this.vx=sqrt(abs(this.vx));
}
if (this.y>height-this.size/2) {
this.y=height-this.size/2;
this.vy=-sqrt(abs(this.vy));
} else if (this.y<0+this.size/2) {
this.y=this.size/2;
this.vy=sqrt(abs(this.vy));
}
}
accelerate() { // this is responsible for the gravity-like acceleration
let d = dist(this.x,this.y,width/2,height/2); // distance from center
let ug = 500*this.size/pow(d,3.3); // custom unit gravity
let ax = (width/2 - this.x)*ug;
let ay = (height/2 - this.y)*ug;
this.vx+=ax;
this.vy+=ay;
}
update() {
this.accelerate();
this.move();
this.draw();
}
draw() {
circle(this.x,this.y,this.size); // draws the particle
}
}
// // Credit to Yong Wang@https://stackoverflow.com/a/61511955
// function waitForElm(selector) {
// return new Promise(resolve => {
// if (document.querySelector(selector)) {
// return resolve(document.querySelector(selector));
// }
// const observer = new MutationObserver(mutations => {
// if (document.querySelector(selector)) {
// resolve(document.querySelector(selector));
// observer.disconnect();
// }
// });
// observer.observe(document.body, {
// childList: true,
// subtree: true
// });
// });
// }
// waitForElm('canvas').then((cvs) => {
// cvs.style.width='100%';
// cvs.style.height='auto';
// });