xxxxxxxxxx
83
// x, vx, ax -> position, velocity, acceleration on x axis
let ParticleCnt = 100; // number of particles
let p = []; // an array of particles objects
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';
colorMode(HSB,100);
for (let i=0;i<ParticleCnt;i++) {
append(p,new Particle());
}
}
function draw() {
background(0);
fill(80);
for (let i=0;i<p.length;i++) {
p[i].update();
stroke(i%100,i%100,80);
strokeWeight(2);
line(p[i].x,p[i].y,width/2,height/2);
}
}
class Particle {
constructor() {
this.size = 10;
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); // 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
}
}