three.js如何添加阴影

添加好 场景 相机 渲染器

添加光 物体和平面:

最后渲染:

添加阴影的步骤:开通相应的true:

完整代码:

<script setup>
// 导入 threejs
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// 创建场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb); // 浅蓝色

// 创建相机
const camera = new THREE.PerspectiveCamera(
  45, // 视角
  window.innerWidth / window.innerHeight,
  0.1, // 近平面
  1000 // 远平面
);
// 设置相机位置  我的视角
camera.position.z = 5;
camera.position.x = 2;
camera.position.y = 10;
camera.lookAt(0, 0, 0);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;//阴影1
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


// 添加坐标辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();

// 添加环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // 白色环境光,强度为0.5
scene.add(ambientLight);

// 添加平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1); // 白色平行光,强度为1
directionalLight.castShadow = true;//阴影2
directionalLight.position.set(5, 10, 7.5); // 设置光源位置
scene.add(directionalLight);


// 球体
const sphereGeometry = new THREE.SphereGeometry(1, 20, 20);
const material = new THREE.MeshStandardMaterial({ color: 0x808080 }); // 灰色
const sphere = new THREE.Mesh(sphereGeometry, material);
sphere.castShadow = true;//阴影3
scene.add(sphere);

// 创建平面
const planeGeometry = new THREE.PlaneGeometry(10, 10)
const plane = new THREE.Mesh(planeGeometry, material);
plane.position.set(0,-1,0);
plane.rotation.x = -Math.PI / 2;
plane.receiveShadow = true;//阴影4
scene.add(plane)





// 渲染函数
function animate() {
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
}
animate();

</script>

<style>
* {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值