使用阴影
1.给立方体添加castShadow,让立方体产生阴影
cube.castShadow = true;
2.创建一个地面用于接收阴影
const planeGemetry = new THREE.PlaneGeometry(20, 30)
const planeMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff })
const plane = new THREE.Mesh(planeGemetry, planeMaterial)
plane.rotateZ(20);
plane.position.z = -10;
plane.position.x = 3;
// 使用平面接收阴影
plane.receiveShadow = true;
scene.add(plane);
3.设置灯光开启阴影
spotLight.castShadow = true;
4.渲染器添加可以使用阴影的能力
renderer.shadowMap.enabled = true;
完整代码
<template>
<div>
<canvas ref="container"
height="700"
width="1400"></canvas>
</div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { THREE, CameraControls } from "@/global/three";
const container = ref(null);
// 创建渲染器
const createRenderer = () => new THREE.WebGLRenderer({ canvas: container.value, antialias: true });
// 创建相机
const createCamera = (options = {}) => {
const { fov, aspect, near, far, positions, eyesP } = {
fov: 40,
aspect: 2,
near: 0.1,
far: 1000,
positions: [0, 50, 0],
eyesP: [0, 0, 0],
...options
}
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(...positions);
camera.lookAt(...eyesP)
return camera
}
onMounted(() => {
const clock = new THREE.Clock();
const renderer = createRenderer();
const camera = createCamera({
positions: [0, 0, 20]
});
const controls = new CameraControls(camera, container.value)
const scene = new THREE.Scene();
// 创建一个立方体
const cubeGemometry = new THREE.BoxGeometry(2, 2, 2)
const cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000, wireframe: false, side: THREE.DoubleSide })
const cube = new THREE.Mesh(cubeGemometry, cubeMaterial)
// 让三维物体 产生阴影,使用平面接收阴影
cube.castShadow = true;
scene.add(cube)
// 创建一个地面用于接收阴影
const planeGemetry = new THREE.PlaneGeometry(20, 30)
const planeMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff })
const plane = new THREE.Mesh(planeGemetry, planeMaterial)
plane.rotateZ(20);
plane.position.z = -10;
plane.position.x = 3;
// 使用平面接收阴影
plane.receiveShadow = true;
scene.add(plane);
// 添加灯光
const spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(-10, 10, 90);
// 设置灯光开启阴影
spotLight.castShadow = true;
scene.add(spotLight);
renderer.shadowMap.enabled = true;
function render () {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
const delta = clock.getDelta();
controls.update(delta);
renderer.render(scene, camera)
requestAnimationFrame(render)
}
requestAnimationFrame(render)
});
</script>
<style lang="scss" scoped></style>