API

Getting Started - Chapter 7 - Day to Night

Day to Night

One useful way to add a graphical user interface to a scene is the Babylon.js GUI. When working in virtual reality, this GUI is necessary because it is designed to be within, and part of, the Babylon.js scene canvas rather than the HTML document. This GUI is pre-loaded into the playground, but in your own projects it requires an additional script:

<script>https://cdn.babylonjs.com/gui/babylon.gui.min.js</script>

For the village world, we will use a GUI stack panel to contain two GUI elements: a text block for the heading and a slider bar to change day to night and back by setting the intensity of the light.

The first thing we need to do is create a special texture, called an AdvancedDynamicTexture, on which the GUI elements will be drawn.

import { AdvancedDynamicTexture } from "@babylonjs/gui/2D/advancedDynamicTexture";
const adt = AdvancedDynamicTexture.CreateFullscreenUI("UI");

For our world, the GUI will be full-screen.

We create the container panel to hold the other elements in the bottom right corner of the screen. Then add it to the advanced dynamic texture.

import { Control } from "@babylonjs/gui/2D/controls/control";
import { StackPanel } from "@babylonjs/gui/2D/controls/stackPanel";
const panel = new StackPanel();
panel.width = "220px";
panel.top = "-50px";
panel.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT;
panel.verticalAlignment = Control.VERTICAL_ALIGNMENT_BOTTOM;
adt.addControl(panel);

Next, create the text block and add it to the panel.

import { TextBlock } from "@babylonjs/gui/2D/controls/textBlock";
const header = new TextBlock();
header.text = "Night to Day";
header.height = "30px";
header.color = "white";
panel.addControl(header);

We create and add the slider to the panel.

import { Slider } from "@babylonjs/gui/2D/controls/sliders/slider";
const slider = new Slider();
slider.minimum = 0;
slider.maximum = 1;
slider.borderColor = "black";
slider.color = "#AAAAAA";
slider.background = "#white";
slider.value = 1;
slider.height = "20px";
slider.width = "200px";
panel.addControl(slider);

We need to add an observable event to the slider in order to change the light intensity.

slider.onValueChangedObservable.add((value) => {
if (light) {
light.intensity = value;
}
});

Now we can control the light in our village world.

Adding a Gui Slider

Where there is light there are shadows. In Babylon.js this is only true when you make it true.