xxxxxxxxxx
103
// Incomplete but for okay for the practice
// terms: x, vx, ax -> position, velocity, acceleration on x axis
let ParticleCnt = 5000; // number of particles
let particles = []; // array of 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';
background(0);
colorMode(HSB,100);
noStroke();
randomSeed(3);
for (let i=0;i<ParticleCnt;i++) {
append(particles,new Particle()); // add new particles to the array
}
}
function draw() {
// everything darkens over time to show particle tails
// maybe can use this to create gradation?
background('rgba(0,0,0, 0.08)');
for (let i=0;i<particles.length;i++) {
fill(i%100,i%100,95); // since 100 is the max color, fill with %100
particles[i].update(); // check object function
}
}
class Particle {
constructor() {
this.size = random(3,10); // random size
this.vx = random(-3,3); // initial x velocity
this.vy = random(-3,3); // initial y velocity
this.ox=this.size/2 + random(width-this.size); // initial x position
this.oy=this.size/2 + random(height-this.size); // initial y position
this.x=this.ox;
this.y=this.oy;
}
init() {
this.size = random(3,10); // random size
this.vx = random(-3,3); // initial x velocity
this.vy = random(-3,3); // initial y velocity
this.x=this.size/2 + random(width-this.size); // initial x position
this.y=this.size/2 + random(height-this.size); // initial y position
}
move() {
this.x += this.vx; // simply add velocity to the position
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=-(this.vx); // sqrt for drastic reduction of speed
} else if (this.x<0+this.size/2) {
this.x=this.size/2;
this.vx=(abs(this.vx));
}
if (this.y>height-this.size/2) {
this.y=height-this.size/2;
this.vy=-(abs(this.vy));
} else if (this.y<0+this.size/2) {
this.y=this.size/2;
this.vy=(abs(this.vy));
}
}
// this is responsible for the gravity-like acceleration
// curved motions and change in velocity are generated by this
accelerate() {
let multiplier = (frameCount%200>100) ? 1:-1;
let d = max(10,dist(this.x,this.y,mouseX,mouseY)); // d from center
let ug = 200*this.size/pow(d,3); // custom unit gravity
let ax = multiplier*(mouseX - this.x)*ug;
let ay = multiplier*(mouseY - this.y)*ug;
this.vx+=ax; // add acceleration to velocity
this.vy+=ay;
this.vx*=0.9;
this.vy*=0.9;
}
update() {
this.accelerate(); // change speed
this.move(); // change position
this.draw(); // draw particle (self)
}
draw() {
circle(this.x,this.y,5); // draws the particle
}
}