JSFiddle - React, Tailwind, and code Playground
by gerdonabbink
HTML
<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>
CSS
html,
body {
margin: 0;
padding: 0;
}
JavaScript
const MIN_SPHERE_RADIUS = 20;
const MAX_SPHERE_RADIUS = 50;
const LOCATION_FROM_CENTER = 100;
const SPHERES = 2;
const DENSITY = 2.65;
let spheres = [];
let center = new THREE.Vector3(0, 0, 0);
let count = 0;
let updateSpheres = function() {
spheres.forEach(sphere => {
spheres.forEach(other => {
if (sphere !== other) {
let distance = sphere.position.distanceTo(other.position);
let direction = sphere.position.clone().sub(other.position);
/* console.log(distance - (sphere.geometry.parameters.radius + other.geometry.parameters.radius)) */;
if (distance - (sphere.geometry.parameters.radius + other.geometry.parameters.radius) <= 0) {
other.position.add(direction.clone().normalize().multiplyScalar(distance - (sphere.geometry.parameters.radius + other.geometry.parameters.radius)));
} else {
let forceMagnitude = (sphere.mass * other.mass) / Math.pow(distance, 2.5);
let force = direction.clone().normalize().multiplyScalar(forceMagnitude);
other.position.add(force);
}
}
});
});
};
function calculateMass(radius) {
return DENSITY * ((4 / 3) * Math.PI * Math.pow(radius, 2));
}
let setupObjects = function() {
for (let x = 0; x < SPHERES; x++) {
let sphereRadius = Math.floor(Math.random() * (MAX_SPHERE_RADIUS - MIN_SPHERE_RADIUS)) + MIN_SPHERE_RADIUS;
let geometry = new THREE.SphereGeometry(sphereRadius, 50, 50);
let sphere = new THREE.Mesh(geometry);
sphere.mass = calculateMass(sphereRadius);
let direction = getRandomVector().normalize();
let minDistance = 200 * 5;
let maxDistance = minDistance + 0.5;
direction.multiplyScalar(Math.random() * (maxDistance - minDistance) + minDistance);
sphere.position.add(direction);
spheres.push(sphere);
...