Make a cloth simulation using babylon.js in HTML + JS (one file)
- User
Make a cloth simulation using babylon.js in HTML + JS (one file)
- Assistant
Make a cloth simulation using babylon.js in HTML + JS (one file)
Here is an HTML file containing a cloth simulation using Babylon.js and Ammo.js. This single file includes all the necessary code to create a cloth that reacts to physics like a real fabric. The cloth is pinned at its top edge and drapes under gravity, colliding with the ground. Simply save this code as an .html file and open it in a modern web browser to see the simulation in action.
<!DOCTYPE html>
<html>
<head>
<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;
user-select: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<!-- Include Babylon.js from CDN -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- Include Ammo.js from CDN -->
<script src="https://cdn.babylonjs.com/ammo.js"></script>
<!-- Our JavaScript code -->
<script>
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
// Create the scene function
const createScene = function () {
// Create a scene
const scene = new BABYLON.Scene(engine);
// Create a camera and position it
const camera = new BABYLON.ArcRotateCamera('camera1', -Math.PI / 2, Math.PI / 2.5, 25, new BABYLON.Vector3(0, 5, 0), scene);
camera.attachControl(canvas, true);
// Create a hemispheric light
const light = new BABYLON.HemisphericLight('light', new BABYLON.Vector3(0, 1, 0), scene);
// Return the scene
return scene;
};
const scene = createScene();
// Wait for Ammo.js to be ready
Ammo().then(() => {
// Enable physics
const gravityVector = new BABYLON.Vector3(0, -9.81, 0);
const physicsPlugin = new BABYLON.AmmoJSPlugin(true);
scene.enablePhysics(gravityVector, physicsPlugin);
// Create ground
const ground = BABYLON.Mesh.CreateGround('ground', 40, 40, 2, scene);
ground.position.y = 0;
ground.physicsImpostor = new BABYLON.PhysicsImpostor(ground, BABYLON.PhysicsImpostor.BoxImpostor,
{ mass: 0, restitution: 0.9 }, scene);
// Create the cloth mesh
const subdivisions = 31;
const cloth = BABYLON.MeshBuilder.CreateGround('cloth', { width: 10, height: 10, subdivisions: subdivisions }, scene);
cloth.position.y = 15;
cloth.rotation.z = Math.PI / 2;
// Get the positions array
const positions = cloth.getVerticesData(BABYLON.VertexBuffer.PositionKind);
// Find the maximum Y coordinate (after rotation)
let maxY = -Infinity;
for (let i = 0; i < positions.length; i += 3) {
const y = positions[i + 1];
if (y > maxY) {
maxY = y;
}
}
// Collect indices of vertices at maxY (top edge)
const fixedPoints = [];
for (let i = 0; i < positions.length / 3; i++) {
const y = positions[i * 3 + 1];
if (Math.abs(y - maxY) < 0.01) {
fixedPoints.push(i);
}
}
// Create soft body physics impostor for the cloth
cloth.physicsImpostor = new BABYLON.PhysicsImpostor(cloth, BABYLON.PhysicsImpostor.SoftbodyImpostor,
{
mass: 1,
pressure: 1500,
dampingFactor: 0.01,
friction: 0.2,
margin: 0.05,
fixedPoints: fixedPoints,
collisionMargin: 0.05
}, scene);
// Add material to the cloth
cloth.material = new BABYLON.StandardMaterial('clothMat', scene);
cloth.material.diffuseColor = new BABYLON.Color3(0.8, 0.2, 0.2);
});
// Register a render loop to repeatedly render the scene
engine.runRenderLoop(function () {
scene.render();
});
// Watch for browser/canvas resize events
window.addEventListener('resize', function () {
engine.resize();
});
</script>
</body>
</html>
Instructions:
.html extension, for example, cloth_simulation.html.Explanation:
Babylon.js and Ammo.js Inclusion: The HTML file includes Babylon.js and Ammo.js using script tags that point to their CDNs.
Canvas Setup: A canvas element with the ID renderCanvas is created to serve as the rendering surface for Babylon.js.
Scene Creation:
Physics Initialization:
Ammo().then()), the physics engine is enabled in the scene using the Babylon.AmmoJSPlugin.Ground Creation:
Cloth Mesh Creation:
BABYLON.MeshBuilder.CreateGround, which provides a grid of vertices suitable for cloth simulation.Fixed Points Calculation:
fixedPoints array. These vertices are pinned in space to simulate the cloth hanging from a line.Soft Body Physics Impostor:
SoftbodyImpostor which enables soft body physics simulation.mass, pressure, dampingFactor, and friction are set to simulate realistic cloth behavior.fixedPoints array is passed to the impostor to fix those vertices in place.Material Assignment:
Rendering Loop:
Window Resize Handling:
Result:
When you open the HTML file in your browser, you will see a red cloth hanging from its top edge and draping naturally under gravity. You can interact with the scene using mouse or touch controls:
Note:
Feel free to adjust the parameters in the code (like mass, pressure, subdivisions, etc.) to see how they affect the cloth simulation.
Not yet included in a published release.