!!!
//开启渲染器的阴影计算renderer.shadowMap.enabled=true
// 设置光照投射阴影开启
DirectionalLight.castShadow = true
// 设置物体投射阴影开启
cube.castShadow = true
// 设置地面接收物体阴影开启
cube2.receiveShadow=true
<script setup>
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 1、创建场景
const scene = new THREE.Scene();
// 2、创建相机
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// 设置相机位置
camera.position.set(2, 4, 15);
scene.add(camera);
// 初始化渲染器
const renderer = new THREE.WebGLRenderer();
// 设置渲染的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);
// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 添加物体
// 创建几何体
const cubeGeometry = new THREE.SphereGeometry(1, 10, 10);
const material = new THREE.MeshStandardMaterial();
// 根据几何体和材质创建物体
const cube = new THREE.Mesh(cubeGeometry, material);
// 将几何体添加到场景中
let material2 = new THREE.MeshStandardMaterial()
const cubeGeometry2 = new THREE.PlaneGeometry(10,10)
const cube2 = new THREE.Mesh(cubeGeometry2,material2)
cube2.rotation.x=-Math.PI/2
cube2.position.y=-2
// 设置物体投射阴影开启
cube.castShadow = true
// 设置地面接收物体阴影开启
cube2.receiveShadow=true
scene.add(cube);
scene.add(cube2)
//开启渲染器的阴影计算
renderer.shadowMap.enabled=true
// 使用渲染器,通过相机将场景渲染进来
function render() {
//如果后期需要控制器带有阻尼效果,或者自动旋转等效果,就需要加入controls.update()
controls.update()
renderer.render(scene, camera);
// 渲染下一帧的时候就会调用render函数
requestAnimationFrame(render);
}
window.addEventListener('resize', onWindowResize, false);
// 灯光
// 环境光
const light = new THREE.AmbientLight(0xffffff,0.5)
scene.add(light)
//直线光源
const DirectionalLight= new THREE.DirectionalLight(0xffffff,0.5)
DirectionalLight.position.set(10,10,10)
// 设置光照投射阴影开启
DirectionalLight.castShadow = true
scene.add(DirectionalLight)
// 定义窗口大小改变时的回调函数
function onWindowResize() {
// 获取窗口大小
var width = window.innerWidth;
var height = window.innerHeight;
// 设置相机投影矩阵的宽高比和视口大小
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
render();
</script>
<template></template>
<script>
export default {};
</script>
<style>
</style>
ThreeJS投射阴影的使用
最新推荐文章于 2024-10-29 10:06:15 发布