Lighting and Shadows in Three.js
Lighting and shadows play a crucial role in creating realistic and visually appealing 3D scenes in Three.js. By properly configuring lights and enabling shadows, you can enhance the depth and realism of your scenes.
1. Types of Lights
Three.js supports various types of lights that can be used to illuminate your scene:
- AmbientLight: Provides global illumination that affects all objects equally, simulating indirect lighting.
- DirectionalLight: Emits light from a specified direction, similar to sunlight.
- PointLight: Emits light uniformly in all directions from a specified point in space, similar to a light bulb.
- SpotLight: Emits light in a cone-shaped beam from a specified point, similar to a flashlight.
- HemisphereLight: Provides ambient and directional lighting based on two colors, simulating the sky and ground.
Each type of light has properties that can be adjusted to control factors such as color, intensity, position, and angle.
2. Enabling Shadows
To enable shadows in your Three.js scene, you need to configure both the renderer and the lights:
- Renderer: Set the
shadowMapEnabled
property of the renderer totrue
to enable shadow mapping. - Lights: Set the
castShadow
property of the lights totrue
to allow them to cast shadows, and set thereceiveShadow
property of objects totrue
to allow them to receive shadows.
Additionally, you can adjust properties such as shadowMapSize
, shadowBias
, and
shadowCameraNear
/shadowCameraFar
to fine-tune the appearance and quality of shadows.
3. Example: Adding Lights and Shadows
Here's an example of adding directional and ambient lights with shadows to a Three.js scene:
// Create directional light with shadows
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 10, 0);
directionalLight.castShadow = true;
scene.add(directionalLight);
// Create ambient light
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Enable shadows in the renderer
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Create a cube that casts and receives shadows
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.castShadow = true;
cube.receiveShadow = true;
scene.add(cube);
In this example, we create a directional light and an ambient light, both with shadows enabled. We then configure the renderer to enable shadow mapping with soft shadows. Finally, we create a cube that both casts and receives shadows and add it to the scene.
By carefully configuring lights and shadows in Three.js, you can achieve realistic lighting effects and enhance the visual quality of your 3D scenes.
Comments
Post a Comment