API

Getting Started - Chapter 7 - Adding Shadows

Adding Shadows

The light we have been using so far, the HemisphericLight, gives an ambient background light and is not suitable for producing shadows. We could use the lamp spot lights; however, the shadows they produce can be faint, so we will introduce a directional light.

import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight";
const light = new DirectionalLight("dir", direction, scene);

As usual, the direction is a Vector3 and the scene parameter is optional.

Setting its position will affect the direction and length of any created shadows.

import { Vector3 } from "@babylonjs/core/Maths/math.vector";
light.position = new Vector3(0, 15, -30);

Shadows will appear only when a ShadowGenerator object is created, a mesh is set to cast the shadow, and the mesh receiving the shadow is set to receive shadows.

import { ShadowGenerator } from "@babylonjs/core/Lights/Shadows/shadowGenerator";
const shadowGenerator = new ShadowGenerator(1024, light);

The first parameter is the size of the shadow map, and the second is the light generating the shadow.

We also need to add a mesh that will cast the shadow.

shadowGenerator.addShadowCaster(casting_mesh, true);

The optional second parameter, which has a default value of false, will add any children of the mesh to the shadow caster.

Finally we also have to tell the mesh on which the shadow is cast to receive it.

receiving_mesh.receiveShadows = true

In our case, at the appropriate positions, we need

import { ShadowGenerator } from "@babylonjs/core/Lights/Shadows/shadowGenerator";
const shadowGenerator = new ShadowGenerator(1024, light);
shadowGenerator.addShadowCaster(dude, true);
ground.receiveShadows = true;
Adding Basic Shadows

Putting this into our world, with suitable value adjustments, gives

Shadows in the Village

So far we have had only one way to view our village world. There are other possibilities with different cameras.