Babylon.js Collisions — Mesh Intersection and Physics
In this tutorial, you will learn about Babylon.js Collisions. We cover key concepts, practical examples, and best practices to help you master this topic.
Babylon.js collision detection provides mesh intersection, raycasting, pick events, and physics-based collision responses for interactive 3D applications.
What You'll Learn
By the end of this guide, you will check mesh-to-mesh intersection, use ActionManager for pointer-based collisions, perform raycasting for line-of-sight, implement physics-based collision detection, and use octree for spatial queries.
Mesh Intersection
if (box1.intersectsMesh(box2)) {
console.log('Boxes overlap');
}
// Check with precise bounding box
if (box1.intersectsMesh(box2, true)) {
console.log('Boxes overlap precisely');
}
ActionManager Pointer Events
box.actionManager = new BABYLON.ActionManager(scene);
box.actionManager.registerAction(
new BABYLON.ExecuteCodeAction(
BABYLON.ActionManager.OnPickTrigger,
function() { console.log('Box clicked'); }
)
);
Raycasting
var ray = new BABYLON.Ray(
camera.position,
camera.getDirection(BABYLON.Axis.Z),
100
);
var pick = scene.pickWithRay(ray);
if (pick.hit) {
console.log('Ray hit:', pick.pickedMesh.name);
pick.pickedMesh.position.y += 1;
}
Physics Collisions
sphere.physicsBody.onCollisionEndedObservable.add(function(collider) {
if (collider.mesh.name === 'ground') {
console.log('Sphere hit ground');
}
});
Common Mistakes
1. Intersection Disabled
Scene auto-close for performance. Enable: scene.meshCollisionEnabled = true.
2. Ray Origin Inside Mesh
Rays starting inside a mesh may not detect it. Offset ray origin slightly.
3. ActionManager Missing
Meshes need an ActionManager to respond to pointer events. Create and assign one.
4. Precise Intersection Is Slow
precise: true checks vertex positions. Use for simple shapes, false for complex.
5. Physics Collision Not Firing
Check that physics engine is enabled and bodies have proper collision group masks.
Practice Questions
Q1: How do you check if two meshes overlap? A: Call mesh1.intersectsMesh(mesh2).
Q2: How do you detect a click on a mesh? A: Register an OnPickTrigger action on the mesh's ActionManager.
Q3: How do you cast a ray from camera? A: Create a BABYLON.Ray from camera position and direction, call scene.pickWithRay.
Q4: How do you enable mesh collisions? A: Set scene.meshCollisionEnabled = true and individual mesh checkCollisions = true.
Q5: How do you get the first mesh under the mouse? A: Use scene.pick(event.pointerX, event.pointerY) for 2D-to-3D picking.
Challenge: Build a shooting gallery with targets that detect bullet hits via raycasting. Each target falls when hit and respawns after 2 seconds.
FAQ
Try It Yourself
Build a clickable box with raycasting.
<!DOCTYPE html>
<html>
<head>
<title>Babylon.js Collisions</title>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<h2>Collision Detection</h2>
<p>Click on the box or sphere</p>
<canvas id="renderCanvas" style="width:100%;height:400px;border-radius:8px;"></canvas>
<script>
var canvas = document.getElementById('renderCanvas');
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.ArcRotateCamera('camera', -Math.PI/2, Math.PI/3, 8, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
new BABYLON.HemisphericLight('light', new BABYLON.Vector3(0, 1, 0), scene);
var box = BABYLON.MeshBuilder.CreateBox('box', { size: 1.5 }, scene);
box.position.x = -2;
box.position.y = 0.75;
var sphere = BABYLON.MeshBuilder.CreateSphere('sphere', { diameter: 1.5 }, scene);
sphere.position.x = 2;
sphere.position.y = 0.75;
var ground = BABYLON.MeshBuilder.CreateGround('ground', { width: 10, height: 10 }, scene);
// ActionManager for click detection
box.actionManager = new BABYLON.ActionManager(scene);
box.actionManager.registerAction(
new BABYLON.ExecuteCodeAction(
BABYLON.ActionManager.OnPickTrigger,
function() {
box.position.y += 0.5;
box.material = box.material || new BABYLON.StandardMaterial('mat', scene);
box.material.diffuseColor = new BABYLON.Color3(1, 0.3, 0.2);
}
)
);
sphere.actionManager = new BABYLON.ActionManager(scene);
sphere.actionManager.registerAction(
new BABYLON.ExecuteCodeAction(
BABYLON.ActionManager.OnPickTrigger,
function() {
sphere.position.y += 0.5;
sphere.material = sphere.material || new BABYLON.StandardMaterial('mat2', scene);
sphere.material.diffuseColor = new BABYLON.Color3(0.2, 0.6, 1);
}
)
);
engine.runRenderLoop(function() { scene.render(); });
window.addEventListener('resize', function() { engine.resize(); });
</script>
</body>
</html>
What's Next
Use action system.
Actions — Advanced action system. Loading Scenes — Loading and exporting scenes.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro