JSFiddle - React, Tailwind, and code Playground
HTML
<body style="background-color:black;">
<canvas id="canvas" width="600" height="450"></canvas><br>
<font color="white">
Simulation speed
<input type="range" id="speedSlider" value="10">
<div id="speed">1x</div>
</font>
</body>
JavaScript
const F = 1000000,
D = 0.95,
UPDATES_PER_SECOND = 100;
let simulationSpeed = 1;
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {return Math.sqrt(this.x * this.x + this.y * this.y);}
neg() {return new Vec(-this.x, -this.y);}
add(v) {return new Vec(this.x + v.x, this.y + v.y);}
sub(v) {return this.add(v.neg());}
mul(d) {return new Vec(this.x * d, this.y * d);}
div(d) {return this.mul(1/d);}
equals(v) {return this.x === v.x && this.y === v.y;}
toString() {return "Vec(" + this.x + ", " + this.y + ")";}
}
class Circle {
constructor(a) {
this.pos = a.pos || new Vec(0, 0);
this.radius = typeof a.radius === "number" ? a.radius : 10;
this.velocity = a.velocity || new Vec(0, 0);
this.color = a.color || "black";
}
updateForce(positions, maxDist) {
this.force = new Vec(0, 0);
positions.forEach(p => {
if(p.equals(this.pos)) return;
let dv = this.pos.sub(p),
dist = dv.length();
if(dist > maxDist) return;
if(dist < 1) dist = 1;
let f = dv.mul(F/(dist*dist*dist));
this.force = this.force.add(f);
});
}
updateVelocity(dt) {
this.velocity = this.velocity.add(this.force.mul(dt)).mul(D);
}
updatePos(dt) {
this.pos = this.pos.add(this.velocity.mul(dt));
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
}
function duplicatePos(elems, vectors) {
return vectors.map(v => elems.map(e => e.pos.add(v)))
.reduce((a, b) => a.concat(b), []);
}
function start() {
const canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
elems = [];
let slider = document.getElementById("speedSlider");
slider.onchange = slider.oninput = e => {
simulationSpeed = slider.value/10;
...