Using babylon.js create a 3d ball in center and simulate cloth simulation, user can click and spawn cloth that falls and interact with ball, provide full code in one file
Assistant
Sure! Below is a complete HTML file that uses Babylon.js to create a 3D scene with a central ball and allows the user to click to spawn cloth that falls and interacts with the ball. The cloth simulation is achieved using a simple physics-based approach with particle joints to simulate the cloth behavior.
Save this code as an .html file and open it in a web browser to see it in action.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Babylon.js Cloth Simulation</title>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
<!-- Include Babylon.js library -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- Include Babylon.js physics engine plugin -->
<script src="https://preview.babylonjs.com/ammo.js"></script>
<script src="https://preview.babylonjs.com/babylon.physics.js"></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script>
// Get the canvas element
const canvas = document.getElementById("renderCanvas");
// Initialize Babylon.js engine and create a scene
const engine = new BABYLON.Engine(canvas, true);
const createScene = function () {
const scene = new BABYLON.Scene(engine);
// Enable physics using Ammo.js
scene.enablePhysics(new BABYLON.Vector3(0, -9.81, 0), new BABYLON.AmmoJSPlugin());
// Create an ArcRotateCamera
const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 20, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// Add a hemispheric light
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Create the central ball
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 4 }, scene);
sphere.position.y = 2;
sphere.physicsImpostor = new BABYLON.PhysicsImpostor(
sphere,
BABYLON.PhysicsImpostor.SphereImpostor,
{ mass: 0, restitution: 0.9 },
scene
);
// Function to create a cloth
const createCloth = function (position) {
// Cloth dimensions
const clothWidth = 3;
const clothHeight = 3;
const clothResolution = 15; // Number of particles along width and height
// Create a grid of spheres (particles)
const particles = [];
const particleDiameter = 0.2;
const mass = 0.1;
const startX = position.x - clothWidth / 2;
const startY = position.y;
const startZ = position.z - clothHeight / 2;
for (let i = 0; i < clothResolution; i++) {
particles[i] = [];
for (let j = 0; j < clothResolution; j++) {
const sphere = BABYLON.MeshBuilder.CreateSphere("particle", { diameter: particleDiameter }, scene);
sphere.position.x = startX + (clothWidth * i) / (clothResolution - 1);
sphere.position.y = startY;
sphere.position.z = startZ + (clothHeight * j) / (clothResolution - 1);
// Only pin the top row of particles
const isPinned = j === 0;
const impostorMass = isPinned ? 0 : mass;
sphere.physicsImpostor = new BABYLON.PhysicsImpostor(
sphere,
BABYLON.PhysicsImpostor.ParticleImpostor,
{ mass: impostorMass },
scene
);
particles[i][j] = sphere;
}
}
// Create distance joints between particles
for (let i = 0; i < clothResolution; i++) {
for (let j = 0; j < clothResolution; j++) {
if (i < clothResolution - 1) {
// Horizontal joint
createJoint(particles[i][j], particles[i + 1][j]);
}
if (j < clothResolution - 1) {
// Vertical joint
createJoint(particles[i][j], particles[i][j + 1]);
}
if (i < clothResolution - 1 && j < clothResolution - 1) {
// Diagonal joints
createJoint(particles[i][j], particles[i + 1][j + 1]);
createJoint(particles[i + 1][j], particles[i][j + 1]);
}
}
}
// Create a mesh to display the cloth surface
const clothMesh = BABYLON.MeshBuilder.CreateRibbon("clothMesh", {
pathArray: particles.map(row => row.map(p => p.position.clone())),
sideOrientation: BABYLON.Mesh.DOUBLESIDE,
updatable: true
}, scene);
// Update the cloth mesh each frame
scene.registerBeforeRender(() => {
const positions = clothMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
let index = 0;
for (let j = 0; j < clothResolution; j++) {
for (let i = 0; i < clothResolution; i++) {
const p = particles[i][j].position;
positions[index++] = p.x;
positions[index++] = p.y;
positions[index++] = p.z;
}
}
clothMesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
});
};
// Function to create a physics joint between two particles
const createJoint = function (sphereA, sphereB) {
const joint = new BABYLON.DistanceJoint({
maxDistance: sphereA.position.subtract(sphereB.position).length()
});
sphereA.physicsImpostor.addJoint(sphereB.physicsImpostor, joint);
};
// Handle click event to spawn cloth
scene.onPointerDown = function (evt, pickResult) {
if (pickResult.hit) {
const pickPosition = pickResult.pickedPoint;
createCloth(new BABYLON.Vector3(pickPosition.x, pickPosition.y + 5, pickPosition.z));
}
};
return scene;
};
const scene = createScene();
// Run the render loop
engine.runRenderLoop(function () {
scene.render();
});
// Resize the engine on window resize
window.addEventListener("resize", function () {
engine.resize();
});
</script>
</body>
</html>
Explanation:
Scene Setup:
A Babylon.js scene is created with an ArcRotateCamera, a hemispheric light, and physics enabled using the Ammo.js plugin.
A central sphere is added to the scene with a sphere physics impostor, acting as the ball that the cloth interacts with.
Cloth Simulation:
The cloth is simulated using a grid of particles (small spheres) connected by distance joints to simulate the behavior of a cloth.
Each particle has a physics impostor of type ParticleImpostor. The top row of particles is "pinned" by setting their mass to zero, so they stay in place unless interacted with.
Distance joints are created between neighboring particles to simulate the structural integrity of the cloth.
Rendering the Cloth:
A ribbon mesh is created to visually represent the cloth surface. It's constructed from the positions of the particles.
The cloth mesh is updated every frame to reflect the new positions of the particles as they move under physics simulation.
User Interaction:
The onPointerDown event is used to detect when the user clicks on the scene.
When clicked, a new cloth is spawned above the clicked point, which then falls under gravity and interacts with the ball and other objects in the scene.
Notes:
Make sure to include the Ammo.js physics engine plugin scripts in your HTML file. The above code uses the CDN links.
The performance of the cloth simulation may vary depending on your hardware, as physics simulations can be computationally intensive.
You can adjust the clothResolution variable to create a finer or coarser cloth mesh. Higher values will look smoother but require more computation.
The restitution property in the physics impostors controls the bounciness of the objects. You can adjust it to change how the cloth and ball interact.
This is a basic cloth simulation and doesn't include features like tearing or complex material properties. For more advanced simulations, you might need to integrate a dedicated physics engine or use GPU-based simulations.
Running the Code:
Save the code above as index.html on your local machine.
Open the index.html file in a modern web browser (e.g., Chrome, Firefox).
Click anywhere in the scene to spawn cloth pieces that will fall and interact with the ball.
I hope this helps you create the 3D scene with cloth simulation you were looking for!