Adding Shadows

There are a few ways to bring in shadows. The easiest way is to use shadowCastChildren and have all child meshes (even models) automatically be included as shadow casters.

We will use a floor/ground to have the shadows cast to - that's easy it's just a prop allowShadows. Oh yeah, and a light that is capable of casting shadows!

Note: instead of shadowCastChildren if you know the names of the meshes you want included or excluded then you can use string array props shadowCasters or shadowCastersExcluding. With a ref to the shadow caster you can access as explained below as well with renderList.

Here is the imperative way:

import { Color3, DirectionalLight, ShadowGenerator, MeshBuilder, StandardMaterial } from "@babylonjs/core";
// you need your scene instance
const box = MeshBuilder.CreateBox('box', { size: 2 }, scene);
box.position.y = 3; // so it is above ground to cast a shadow
const ground = MeshBuilder.CreateGround('ground', { width: 6, height: 6 }, scene);
ground.receiveShadows = true;
var light = new DirectionalLight("dl", new Vector3((-5 * Math.PI) / 4, (-5 * Math.PI) / 4, -Math.PI), scene);
light.position = {new Vector3(0, 4, 16);
var shadowGenerator = new ShadowGenerator(1024, light);
shadowGenerator.useBlurExponentialShadowMap = true;
shadowGenerator.blurKernel = 64;
// this is what makes the box cast shadows
shadowGenerator.getShadowMap().renderList.push(box);
<directionalLight
name="dl"
intensity={0.6}
direction={new Vector3((-5 * Math.PI) / 4, (-5 * Math.PI) / 4, -Math.PI)}
position={new Vector3(0, 4, 16)}
>
<shadowGenerator mapSize={1024} useBlurExponentialShadowMap blurKernel={64} shadowCastChildren>
<box name="box" size={2} />
</shadowGenerator>
<directionalLight />
<ground name="ground" height={6} width={6} receiveShadows />

If you have followed on the previous guides then you hopefully were able to follow all of that, but there are definitely a couple of new points that need to be explained!

  1. <shadowGenerator ... /> will delay instantation until an appropriate light source (one that supports shadows) is available as a parent (any ancestor) element.
  2. shadowCastChildren is not a Babylon.js prop - it's a custom react-babylonjs one that takes all children elements that are meshes (even models) and adds/removes them from the shadowMap renderList as they are added/removed from the scene automatically. Custom props are handled in the guide, but otherwise the Babylon.js API describes the properties

Thanks for reading this far! That's it for the guide section for now. The examples go into many specific use cases and highlight other react-babylonjs custom props that are available and also how to use other Babylon.js components and integrate some 3rd party ones.