xxxxxxxxxx
96
// !Warning!: long gaze may result in headache.
//
// For Assignment 3
// Initially inspired by my colloquium class, Life in the Universe.
// Click the canvas to see colored version.
//
// For the simplicity of the project, a "center of the gravity"
// is located at the center of the canvas. All particles accelerate
// toward that point.
//
// Also, to prevent canvas from filling up with colors, while showing
// traces of motions, rgba (20,20,20,0.08) is applied
// Reason why not rgba (0,0,0,0.08) is that too much contrast causes
// headache.
//
// terms: x, vx, ax -> position, velocity, acceleration on x axis
let ParticleCnt = 2000; // 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(50);
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(20,20,20, 0.08)');
for (let i=0;i<particles.length;i++) {
if (mouseIsPressed) {
fill(i%100,i%100,95); // since 100 is the max color, make sure <100
} else {
fill(10,10,80);
}
particles[i].update(); // check object function
}
}
class Particle {
constructor() {
this.init(); // for the resuability of the code, used init() function
}
init() {
this.size = random(1,3); // random size
this.vx = 0; // initial x velocity
this.vy = 0; // 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;
}
// this is responsible for the gravity-like acceleration
accelerate(x,y,m) {
let d = dist(this.x,this.y,x,y); // distance from center
let ug = m*this.size/pow(max(5,d),2.3); // custom unit gravity
let ax = (x - this.x)*ug; // closer to the center, higher ax
let ay = (y - this.y)*ug;
this.vx+=ax; // add acceleration to velocity
this.vy+=ay;
this.vx*=0.02; // slowing down to allow higher velocity shown
this.vy*=0.02; // on canvas without chaos
if (d<50) {this.init();} // 50 is for the size of the black hole
}
update() {
this.accelerate(width/2,height/2,10000); // change speed
this.move(); // change position
this.draw(); // draw particle (self)
}
draw() {
circle(this.x,this.y,this.size); // draws the particle
}
}