Collisions by Gravity – BabylonJS Series part 9

Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

Did you ever play to an FPS (First Person Shooter) game? We are to simulate the same camera movements: the camera is on the floor, in collision with the ground and any objects.

Elements

Final result

How can I do this ?

To replicate this movement, we have to do this in 3 simple steps:

1 – Define and apply gravity

The first thing to do is to define our gravity vector, defining the G force. In a classic world, on earth, the direction of the force of gravity is down on Y axis, but be free to change it!

scene.gravity = new BABYLON.Vector3(0, -9.81, 0);

Gravity can be applied to any camera that you have defined previously in your code.

camera.applyGravity = true;

2 – Define ellipsoid

An important step is now to define the ellipsoid around our camera. This ellipsoid is representing our player’s dimensions: a collision event will be raised when a mesh will be in contact with this ellipsoid, preventing camera to be too close to this mesh:

Ellipsoid

This ellipsoid is the one by default, but changing values will make you taller, bigger, or smaller, thinner, depending of the axis.

//Set the ellipsoid around the camera (e.g. your player's size)
camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);

3 – Apply collision

Finally, when those previous elements are ready, we just have to declare that we are interested in collisions:

// Enable Collisions
scene.collisionsEnabled = true;

And what are the meshes which could be in collision with our camera:

ground.checkCollisions = true;
box.checkCollisions = true;

That’s it!

Now, your camera is going to fall on y-axis until it collide our ground.