threejs - 灯光与阴影

116 阅读1分钟

灯光阴影前提

材质要满足能够对光照有反应;

设置渲染器开启阴影的计算

设置光照投射阴影

设置物体投射阴影

设置物体接收阴影

设置渲染器开启阴影的计算

renderer.shadowMap.enabled = true

设置光照投射阴影

创建灯光

// 灯光
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
directionalLight.position.set(10,10,10)
scene.add(directionalLight)

设置光照投射阴影

castShadow

directionalLight.castShadow = true

设置物体投射阴影

sphere.castShadow = true

设置物体接收阴影

plane.receiveShadow = true

设置阴影贴图模糊度

给灯光设置

directionalLight.shadow.radius = 20

设置阴影贴图分辨率

directionalLight.shadow.mapSize.set(2048, 2048)

设置平行光投射相机的属性

// 近端
directionalLight.shadow.camera.near = 0.5
// 远端
directionalLight.shadow.camera.far = 500
// 上
directionalLight.shadow.camera.top = 5
// 下
directionalLight.shadow.camera.bottom = -5
// 左
directionalLight.shadow.camera.left = -5
// 右
directionalLight.shadow.camera.right = 5

更新摄像机投影矩阵

在摄像机任何参数被修改后调用

directionalLight.shadow.camera.updateProjectionMatrix();