JSFiddle - React, Tailwind, and code Playground

by Mert Ener

HTML

<!DOCTYPE html>
<html>
<head>
<title>gravity fall</title>
</head>
<body>
<article id="box">
<div id="dot1"></div>
<div id="dot2"></div>
</article>
</body>
</html>

CSS

#dot1 {
  position: absolute;
  top:100px;
  left:100px;
  transform: translate(-50%, -50%);
  height: 24px;
  width: 24px;
  background-color: #777;
  border-radius: 50%;
  display: inline-block;
}
#dot2 {
  position: absolute;
  top:400px;
  left:400px;
  transform: translate(-50%, -50%);
  height: 48px;
  width: 48px;
  background-color: #777;
  border-radius: 50%;
  display: inline-block;
}

#box {
  position: relative;
  padding:0;
  margin:0;
  width: 500px;
  min-height: 500px !important;
  height: auto;
  }
  body {
    padding:0;
    margin:0;
    background-color: rgb(30,31,31);
  }

JavaScript

const G = 1;

// Object 1 (initially positioned at some distance from Object 2)
function createObj (el) {
  let obj = {
    x: el.offsetLeft,  // Starting X position
    y: el.offsetTop,  // Starting Y position
    vx: 0,   // Initial X velocity
    vy: 0,   // Initial Y velocity
    radius: el.offsetHeight/2,
    mass: el.offsetHeight/2*10,  // Mass of the object
    getDx: (elo) => {
    
    },
    getDy: (elo) => {
    
    },
    
  }
}
// Object 2 (initially positioned at some distance from Object 1)

// Simulation function
function simulate() {
    // Calculate the distance between the two objects
    const dx = object2.x - object1.x;
    const dy = object2.y - object1.y;
    const distance = (dx ** 2 + dy ** 2) ** (1/2);

    // Check if a collision occurred (distance <= sum of radii)
    if (distance <= object1.radius + object2.radius) {
        // Normal vector (direction of collision)
        const nx = dx / distance;
        const ny = dy / distance;

        // Calculate velocities along the normal direction
        const v1Normal = object1.vx * nx + object1.vy * ny;
        const v2Normal = object2.vx * nx + object2.vy * ny;

        const v1NormalAfter = ((v1Normal * (object1.mass - object2.mass)) + (2 * object2.mass * v2Normal)) / (object1.mass + object2.mass);
        const v2NormalAfter = ((v2Normal * (object2.mass - object1.mass)) + (2 * object1.mass * v1Normal)) / (object1.mass + object2.mass);

        object1.vx += (v1NormalAfter - v1Normal) * nx;
        object1.vy += (v1NormalAfter - v1Normal) * ny;
        object2.vx += (v2NormalAfter - v2Normal) * nx;
        object2.vy += (v2NormalAfter - v2Normal) * ny;
    } else {
        // Calculate gravitational force between object1 and object2 (only if they haven't collided)
        const force = (G * object1.mass * object2.mass) / (distance * distance);

        // Calculate acceleration on each object due to the other
        const ax1 = (force * dx) / (distance * object1.mass);
        const...