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

BabylonJS Series by David Catuhe (@DeltaKosh):

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.

What you could expect

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

Elements

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
camera.attachControl(canvas);

Note that you can change some parameters later, depending of the type of cameras: Change target/position of ArcRotate camera:

arcCamera.target = 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 😉