案例说明:
第一:定义一个平面用来接收阴影的
第二:定义一个物体用来产生阴影的
第三:
代码
- //添加平行光
- const directionalLight = new THREE.DirectionalLight(0xffffff)
- directionalLight.position.set(1, 1, 1) //设置光的位置
- directionalLight.castShadow = true //********
- directionalLight.shadow.mapSize.width = 1024 //默认是512
- directionalLight.shadow.mapSize.height = 1024 //默认是512
- scene.add(directionalLight)//把平行光添加进场景
-
- //定义一个平面(用来接收阴影)
- const planeG = new THREE.PlaneGeometry(4, 4)
- const planeM = new THREE.MeshStanderdMaterial({ color: 0xcccccc })
- const plane = new THREE.Mesh(planeG, planeM)
- plane.rotation.x = -0.5 * Math.PI //让平面旋转90度
- plane.receiveShadow = true //接收阴影 //********
- scene.add(plane) //添加场景
-
- //定义一个球体(被照物体)
- const sphereG = new THREE.SphereGeometry(0.5)//定义一个球半径为0.5
- const sphereM = new THREE.MeshStandardMaterial({
- color: 0xffff00,
- })
- const sphere = new THREE.Mesh(sphereG, sphereM)
- sphere.position .y = 0.5
- sphere.castShadow = true //光线照在物体上产生阴影 //********
- scene.add(sphere)
-
- //渲染阴影
- renderer.shadowMap.enabled = true //渲染阴影 //********
效果图:
这个的阴影比较粗糙

需要光滑就要给光设置
directionalLight.shadow.mapSize.width = 1024 //默认是512
directionalLight.shadow.mapSize.height = 1024 //默认是512

让球动起来
- const clock = new THREE.Clock()
- tick()
- function tick() {
- const time = clock.getElapsedTime()
- //Math.sin(time) 取值范围是-1到1之间
- //Math.abs()是取绝对值
- sphere.position.y = Math.abs(Math.sin(time))
- requestAnimationFrame(tick)
- renderer.render(scene, camere)
- }