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 = 3;
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);
if (distance > sphere.geometry.parameters.radius + other.geometry.parameters.radius) {
let forceMagnitude = (sphere.mass * other.mass) / Math.pow(distance, 2.5);
let force = direction.clone().normalize().multiplyScalar(forceMagnitude);
other.position.add(force);
} else {
other.position.add(direction.clone().normalize().multiplyScalar(distance - (sphere.geometry.parameters.radius + other.geometry.parameters.radius)));
/* console.log('help he is inside') */;
}
}
});
});
};
function calculateMass(radius) {
return DENSITY * (((4 / 3) * Math.PI * Math.pow(radius, 2)) / 100);
}
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);
if (x == 0) {
sphere.position.x += LOCATION_FROM_CENTER;
} else if (x == 1) {
sphere.position.x -= LOCATION_FROM_CENTER;
} else {
sphere.position.z += LOCATION_FROM_CENTER;
}
spheres.push(sphere);
scene.add(sphere);
}
};
let initThree = function() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera =...