Here’s the demo we’re going to build together: Babylon.js Espilit Physics demo with Oimo.js.
![]() |
1. Understanding Collisions
Looking at the Wikipedia collision detection definition, we can read that:
Collision detection typically refers to the computational problem of detecting the intersection of two or more objects. While the topic is most often associated with its use in video games and other physical simulations, it also has applications in robotics. In addition to determining whether two objects have collided, collision detection systems may also calculate time of impact (TOI), and report a contact manifold (the set of intersecting points). Collision response deals with simulating what happens when a collision is detected (see physics engine, ragdoll physics). Solving collision detection problems requires extensive use of concepts from linear algebra and computational geometry.Let’s now unpack that definition into a cool 3D scene that will act as our starting base for this tutorial.
You can move in this great museum as you would in the real world. You won’t fall through the floor, walk through walls, or fly. We’re simulating gravity. All of that seems pretty obvious, but it requires a bunch of computation to simulate that in a 3D virtual world.
The first question we need to resolve when we think about collision detection is how complex it should be. Indeed, testing whether two complex meshes are colliding could cost a lot of CPU, even more with a JavaScript engine where it’s complex to offload that on something other than the UI thread.
To better understand how we’re managing this complexity, navigate into the Espilit museum near this desk:
![]() |
What’s a Collider?
Rather than testing the collisions against the complete detailed meshes, you can put them into simple invisible geometries. Those colliders will act as the mesh representation and will be used by the collision engine instead. Most of the time, you won’t see the differences but it will allow us to use much less CPU, as the math behind that is much simpler to compute.
Every engine supports at least two types of colliders: the bounding box and the bounding sphere. You’ll better understand by looking at this picture:
![]() |
| Extracted from: Computer Visualization, Ray Tracing, Video Games, Replacement of Bounding Boxes |
Let’s go back to the Espilit scene and display the invisible bounding element in a semitransparent red color:
![]() |
Note: if you’d like to start learning Babylon.js, you can follow the free training course at Microsoft Virtual Academy (MVA). For instance, you can jump directly to Introduction to WebGL 3D with HTML5 and Babylon.js: Using Babylon.js for Beginners where we cover this collision part of Babylon.js. You can also have a look at the code inside our interactive playground tool, Babylon.js playground: Collisions sample.
Based on the complexity of the collision or physics engine, there are other types of colliders available: the capsule and the mesh, for instance.
![]() |
| Extracted from: Getting Started with Unity - Colliders & UnityScript |
2. Loading the Starting Scene
To load our Espilit scene, you have various options:
Option 1: Download it from our GitHub repository, and then follow the Introduction to WebGL 3D with HTML5 and Babylon.js: Loading Assets module of our MVA course to learn how to load a .babylon scene. Basically, you need to host the assets and the Babylon.js engine into a web server and set the proper MIME types for the .babylon extension.
Option 2: Download this premade Visual Studio solution (.zip file).
Note: If you are unfamiliar with Visual Studio, take a look at this article: Web developers, Visual Studio could be a great free tool to develop with… Please note also that the Pro version is now free for a lot of different scenarios. It’s named Visual Studio 2013 Community Edition.
Of course, you can still follow this tutorial if you don’t want to use Visual Studio. Here is the code to load our scene. Remember that most browsers support WebGL now—remember to test for Internet Explorer even on your Mac.
- /// <reference path="/scripts/babylon.js" />
- var engine;
- var canvas;
- var scene;
- document.addEventListener("DOMContentLoaded", startGame, false);
- function startGame() {
- if (BABYLON.Engine.isSupported()) {
- canvas = document.getElementById("renderCanvas");
- engine = new BABYLON.Engine(canvas, true);
- BABYLON.SceneLoader.Load("Espilit/", "Espilit.babylon", engine, function (loadedScene) {
- scene = loadedScene;
- // Wait for textures and shaders to be ready
- scene.executeWhenReady(function () {
- // Attach camera to canvas inputs
- scene.activeCamera.attachControl(canvas);
- // Once the scene is loaded, just register a render loop to render it
- engine.runRenderLoop(function () {
- scene.render();
- });
- });
- }, function (progress) {
- // To do: give progress feedback to user
- });
- }
- }
The collision engine is mostly dedicated to the camera interacting with the scene. You can enable gravity or not on the camera, and you can enable the checkCollision option on the camera and on the various meshes.
The collision engine can also help you to know if two meshes are colliding. But that’s all (this is already a lot, in fact!). The collision engine won’t generate actions, force or impulse after two Babylon.js objects are colliding. You need a physics engine for that to bring life to the objects.
The way we’ve been integrating physics in Babylon.js is via a plugin mechanism. You can read more about that here: Adding your own physics engine plugin to Babylon.js. We’re supporting two open-source physics engines: Cannon.js and Oimo.js. Oimo is now the preferred default physics engine.
If you’ve chosen Option 1 to load the scene, you then need to download Oimo.js from our GitHub. It’s a slightly updated version we’ve made to better support Babylon.js. If you’ve chosen Option 2, it’s already referenced and available in the VS solution under the scripts folder.
3. Enabling Physics Support in the Scene and Transforming Colliders Into Physics Impostors
The first thing to do is to enable physics on the scene. For that, please add these lines of code:
- scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.OimoJSPlugin());
- //scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.CannonJSPlugin());
Now, we need to iterate through all non-visible colliders used by the collision engine and activate physics properties on it. For that, you simply need to find all meshes where checkCollisions is set to true but not visible in the scene:
- for (var i = 1; i < scene.meshes.length; i++) {
- if (scene.meshes[i].checkCollisions && scene.meshes[i].isVisible === false) {
- scene.meshes[i].setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, { mass: 0,
- friction: 0.5, restitution: 0.7 });
- meshesColliderList.push(scene.meshes[i]);
- }
- }
- var meshesColliderList = [];
Written by David Rousset
If you found this post interesting, follow and support us.
Suggest for you:
Advanced HTML5 Tutorial for Web Developers
Build Professional Websites with HTML5 and CSS3 from Scratch
Build Responsive Real World Websites with HTML5 and CSS3
Build Real World Websites from Scratch using HTML5 and CSS3
Learn Web Development Using HTML5 Advanced Programing





No comments:
Post a Comment