Computing Stories: Scintillating Simulations

ellipse(width/2, y, 20);
let y = 100;
let vy = 0;
vy += 0.01 // without units;
if (y>height) {
vy* = -1;
}
let position = createVector(100, width/2);
let velocity = createVector(4,0);
function checkBoundaries() {
if (position.x < 0 || position.x > width) {
velocity.x *= -1;
}
if (position.y < 0 || position.y > height) {
velocity.y *= -1;
}
}
function draw() {
velocity.y += 0.01;
position.add(velocity);
checkBoundaries();
ellipse(pos.x,pos.y,20);
}
const g = 0.04;class Ball {
constructor(pos,v,r){
this.pos=pos; // position of ball
this.v = v; // velocity of ball
this.r = r; // radius of ball
}

checkBoundaries() {
// find the position of the ball in the next frame
const pos = this.pos.copy().add(this.v.copy().mult(dt));
if (pos.x + this.r > width || pos.x - this.r < 0) {
this.v.x *= -1;
}
if (pos.y + this.r > height || pos.y - this.r < 0) {
this.v.y *= -1;
}
}

update() {
this.checkBoundaries();
this.v.y += g; // acceleration due to gravity
// change position according to velocity
this.pos.add(this.v.copy().mult(dt));
}

show() {
noStroke();
fill(255);
ellipse(this.pos.x,this.pos.y,this.r*2)
}
}
collide(p) { 
let v1 = this.v.copy();
let v2 = p.v.copy();
let m1 = this.m;
let m2 = p.m;
let x1 = this.pos.copy();
let x2 = p.pos.copy();
let a1 = 2*m2/(m1+m2);
let b1 = v1.copy().sub(v2).dot(x1.copy().sub(x2));
b1 /= x1.copy().sub(x2).magSq();
let c1 = x1.copy().sub(x2).mult(a1*b1);
this.v = v1.copy().sub(c1);
let a2 = 2*m1/(m1+m2);
let b2 = v2.copy().sub(v1).dot(x2.copy().sub(x1));
b2 /= x2.copy().sub(x1).magSq();
let c2 = x2.copy().sub(x1).mult(a2*b2);
p.v = v2.copy().sub(c2);
}
function collisions() {
// for each pair of particles determine if they have collided.
for (let i = 0; i < balls.length - 1; i++) {
for (let j = i + 1; j < balls.length; j++) {
let b1 = balls[i];
let b2 = balls[j];
//calc position based on one step in the future
let pos1 = b1.pos.copy().add(b1.v.copy().mult(dt));
let pos2 = b2.pos.copy().add(b2.v.copy().mult(dt));
if (pos1.dist(pos2) < b1.r + b2.r) {
b1.collide(b2);
}
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store