BabylonJS Scene

Basic Scene with a cube

Overview

We will create our BabylonJS scene on Babylon Playground. Find out more about the editor on What is playground? chapter.

We will implement the 3D concepts we discussed in How to create a basic 3D scene? chapter.

BabylonJS Code

To create a basic BabylonJS scene, we initialize a scene, create camera, light and a mesh and return the scene object.

const createScene =  () => {
    const scene = new BABYLON.Scene(engine);

    const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 3, new BABYLON.Vector3(0, 0, 0));

    const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0));

    const box = BABYLON.MeshBuilder.CreateBox("box", {});

    return scene;
}

Scene object gets engine as the input argument. You don't have to worry about the engine when you are working on the playground but when you are working on your local code sample, we will create the engine as well.

Camera

Arc Rotate Camera acts like a satellite in orbit around a target and always points towards the target position. In our case, it is pointing towards the box. Where ever you move your camera, it will still point to towards the box.

Arc Rotate Camera parameters are: name you want to give to your camera, alpha(radians) the longitudinal rotation, beta beta (radians) the latitudinal rotation, radius(the distance from the target position), target position(center where the box will be created as a default), scene(optional argument). In this code example scene is not given as an argument and defaults to the scene object on the playground.

Setting beta to 0 or PI can, for technical reasons, cause problems.

Light

A hemispheric light is an easy way to simulate an ambient environment light. In our case, we are doing the bare minimum, just giving a name to the light and set it's location.

Setting y location to 1 while our main object is in the center (0,0,0) location will move the light above the object.

Box Mesh

We are creating a Box Mesh by calling BABYLON.MeshBuilder.CreateBox method with the minimum requirements, a name and an options empty object.

Exercise

Next Steps

Continue exploring how to create a 3D scene with other libraries

pageThreeJS Scene

Keep working with BabylonJS and dive deeper into WebXR on the Babylon.js chapter:

pageBabylon.js

Read more on BabylonJS documentation:

Browse community BabylonJS demos:

Last updated