Using a Camera in a 3D WebGL World – BabylonJS Series part 5

BabylonJS Series by David Catuhe (@DeltaKosh):

What you could expect

To continue building our scene, let’s see how to manage cameras.


Final result

How can I do this ?

Cameras management is pretty simple: Babylon.js supports 3 kind of cameras:

  • FreeCamera is a FPS like camera where you control the camera with the cursors keys and the mouse
  • TouchCamera is a camera controlled with touch events (it requires “hand.js” to work, always included in our demos)
  • ArcRotateCamera is a camera that rotates around a given pivot. It can be controlled with the mouse or touch events (and it also requires “hand.js” to work)

You can create as much cameras as you want but only one camera can be active at a time. Here is how to write the code for each of those cameras:

// FreeCamera >> You can move around the world with mouse and keyboard
// Parameters : name, position, scene
    var freeCamera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 0, 5), scene);
// TouchCamera >> Move in your world with your touch screen
// Parameters : name, position, scene
    var touchCamera = new BABYLON.TouchCamera("TouchCamera", new BABYLON.Vector3(0, 0, 10), scene);
// ArcRotateCamera >> Camera turning around a 3D point (here Vector zero)
// Parameters : name, alpha, beta, radius, target, scene
    var arcCamera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);

All the cameras can automatically handle inputs for you by calling “attachControl” function on the canvas. And you can revoke the control by using “detachControl” function:

//Attach the camera to the scene

Note that you can change some parameters later, depending of the type of cameras: Change target/position of ArcRotate camera: = new BABYLON.Vector3(3, 0, 0);
arcCamera.setPosition(new BABYLON.Vector3(0, 0, 50));

Change sensibility of Touch camera:

touchCamera.moveSensibility = 100 ;

Apply gravity to Free camera: later in those tutorials 😉

About the author  ⁄ 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.