xxxxxxxxxx
110
//
// Atoms
// by Philip, January 16, 2021
//
// Basic framework for moving spheres with r, p, v, c.
//
// And collisions
//
let atoms = [];
let num = 100;
let v_initial = 100;
let r_min = 1;
let r_max = 10;
let repeat = false;
let collisions = true;
function setup() {
createCanvas(800, 600);
noStroke();
for (let i = 0; i < num; i++) {
let r = random(r_min, r_max);
let c = color(random(255), random(255), random(255));
let v = createVector(random(-1.0, 1.0), random(-1.0, 1.0)).mult(v_initial);
let p = createVector(random(width), random(height));
atoms[i] = new atom(p, v, r, c, atoms, i);
}
}
function draw() {
background(128);
for (let i = 0; i < num; i++) {
atoms[i].update();
atoms[i].display();
}
noStroke();
strokeWeight(1);
fill(0);
}
// atom class
function atom(p, v, r, c, _others, _id) {
this.p = p.copy();
this.v = v.copy();
this.r = r;
this.c = c;
this.others = _others;
this.id = _id;
this.dt = 1.0/60.0;
this.update = function() {
if (collisions) {
// Check for collisions and add restoring forces
let collisionForces = createVector(0,0,0);
for (let i = 0; i < this.others.length; i++) {
if (i != this.id) {
let d = p5.Vector.sub(this.p, this.others[i].p);
let penetration = ((this.r + this.others[i].r)) - d.mag();
if (penetration > 0) {
d.normalize();
// Elastic component - restitution (note: does not conserve energy)
collisionForces.add(d.mult(10 * penetration));
}
}
}
this.v.add(collisionForces.mult(1.0));
}
this.p.add(p5.Vector.mult(this.v, this.dt));
// Edge conditions
if (repeat) {
if (this.p.x > width) this.p.x -= width;
if (this.p.x < 0) this.p.x += width;
if (this.p.y > height) this.p.y -= height;
if (this.p.y < 0) this.p.y += height;
} else {
if (this.p.x >= width) {
this.v.x *= -1.0;
this.p.x = width - 1;
}
if (this.p.x < 0) {
this.v.x *= -1.0;
this.p.x = 0.0;
}
if (this.p.y >= height) {
this.v.y *= -1.0;
this.p.y = height - 1;
}
if (this.p.y < 0) {
this.v.y *= -1.0;
this.p.y = 0.0;
}
}
}
this.display = function() {
stroke(0);
strokeWeight(1);
fill(this.c);
ellipse(this.p.x, this.p.y, this.r * 2, this.r * 2);
}
};