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!

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

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.

3 – Apply collision

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

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

That’s it!

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

Published by

David Catuhe

David Catuhe is technical evangelist lead at Microsoft France. He defines himself as a geek. He loves to develop with JavaScript and HTML5 but also with DirectX, C#, C++ or even Kinect (He wrote a book about it which is available on Amazon).David has a blog called Eternal Coding where he writes about HTML5, Windows, Kinect and 3D Development.

Share this article

  • alex forselius

    How I do implement a jump in BabylonJS?