JSFiddle - React, Tailwind, and code Playground
by Mert Ener
HTML
<article id="box">
</article>
CSS
div {
position: absolute;
aspect-ratio:1;
transform: translate(-50%, -50%);
background-color: #777;
border-radius: 50%;
display: inline-block;
}
#box {
position: relative;
padding:0;
margin:0;
min-width: 100%;
min-height: 100% !important;
height: auto;
}
body {
padding:0;
margin:0;
background-color: rgb(30,31,31);
}
JavaScript
const N = 3;
let c = 0;
let objs = [];
const G = 0.00001;
let divs = [];
function getPosition(r) {
function setPosition() {
const position = {
x: Math.random() * (800 - 50) + 50,
y: Math.random() * (800 - 50) + 50,
};
for (let i = 0; i < objs.length; i++) {
const dx = objs[i].x - position.x;
const dy = objs[i].y - position.y;
const d = (dx ** 2 + dy ** 2) ** (1 / 2);
if (d < r + objs[i].r) {
return;
}
}
return position;
}
let position;
while (typeof position === "undefined") {
position = setPosition();
}
return position;
}
function addObj() {
let r = Math.random() * (56 - 8) + 8;
let position = getPosition(r);
let obj = {
x: position.x,
y: position.y,
vx: (Math.random() * (Math.random() < 0.5 ? -1 : 1) * 1000) / r ** 2,
vy: (Math.random() * (Math.random() < 0.5 ? -1 : 1) * 1000) / r ** 2,
m: (4 / 3) * 3.14 * r ** 4,
r: r,
};
let node = document.createElement("div");
document.getElementById("box").appendChild(node);
node.style.left = obj.x + "px";
node.style.top = obj.y + "px";
node.style.height = obj.r * 2 + "px";
node.style.backgroundColor =
"#" + Math.floor(Math.random() * 16777215).toString(16);
divs.push(node);
return obj;
}
for (let n = 0; n < N; n++) {
objs.push(addObj());
}
function simulate() {
// --- TÜM ÇİFTLERİ YALNIZCA BİR KERE İŞLE ---
for (let i = 0; i < N; i++) {
for (let k = i + 1; k < N+i; k++) {
let j = k%N;
const dx = objs[j].x - objs[i].x;
const dy = objs[j].y - objs[i].y;
const d = Math.sqrt(dx * dx + dy * dy);
if (d === 0) continue;
const nx = dx / d;
const ny = dy / d;
// --- ÇARPILMIŞLAR MI? ---
if (d < objs[i].r + objs[j].r) {
// ***** ELASTİK ÇARPIŞMA (A ve B aynı anda güncelleniyor) *****
// Normal bileşenleri al
const v1n = objs[i].vx...