
Advanced Lighting and Shadow Techniques (Optional)
In this section, we'll delve into some more advanced lighting and shadow techniques that can significantly enhance the realism and atmosphere of your Three.js scenes. While basic lighting can get you started, mastering these methods will elevate your creations.
Often, a single light source isn't enough to convincingly illuminate a scene. Employing multiple lights allows for more nuanced lighting scenarios, such as simulating ambient light alongside a directional key light, or adding subtle accent lighting. Be mindful of how lights interact, as they can add up their intensities, potentially over-illuminating areas if not managed carefully.
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);While we've touched on shadows, let's explore the underlying mechanism: shadow mapping. Three.js typically uses a technique where the scene is rendered from the light's perspective to create a depth map (the shadow map). This map is then used during the main scene rendering to determine if a pixel is in shadow. Higher resolution shadow maps lead to sharper shadows but come with a performance cost.
To enable shadows for a light, you need to cast shadows and to receive shadows, you need to enable it on the mesh.
// For lights that cast shadows
directionalLight.castShadow = true;
// For meshes that cast and receive shadows
mesh.castShadow = true;
mesh.receiveShadow = true;