In the previous chapters, we've learned how to build and position our 3D objects. Now, it's time to make them look truly alive by introducing light. Just like in the real world, light plays a crucial role in how we perceive shapes, textures, and depth. Three.js offers several types of lights, each with its own characteristics and use cases. Understanding these light types is fundamental to creating visually appealing and realistic 3D scenes.
Let's explore the primary light types available in Three.js:
- Ambient Light: The All-Encompassing Glow
Ambient light is the simplest form of lighting. It's like a general, diffused light that illuminates everything in the scene equally, regardless of its position or orientation. It doesn't cast shadows and doesn't have a direction. Ambient light is great for adding a subtle overall brightness to your scene and preventing completely dark areas. It's often used in conjunction with other light types to soften harsh shadows and give a more balanced look.
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);In this code snippet, 0xffffff represents the color white, and 0.5 is the intensity. You can adjust these values to control the brightness and color of the ambient light.
- Directional Light: The Sun's Rays
Directional light simulates a distant light source, such as the sun. It emits light in a single direction, meaning all rays of light are parallel. This type of light is perfect for creating strong, consistent lighting across your entire scene, and it's the only light type that can cast realistic shadows. The position of a directional light doesn't matter; only its direction does. You define its direction using a Vector3.
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);