three.js 项目搭建(三)——场景搭建

1,894 阅读3分钟

上一篇文章,我们尝试增加一个环境贴图

hdr环境贴图

一个可以免费下载hdr贴图的网站:polyhaven.com/hdris

 import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';

 // 加载hdr环境贴图
  const rgbeLoader = new RGBELoader();
  rgbeLoader.loadAsync('/rgbe3.hdr').then(texture => {
    texture.mapping = THREE.EquirectangularReflectionMapping;
    scene.background = texture;
  });

效果展示: image.png 西瓜有点突兀,哈哈哈,没事,这不重要。

增加光照阴影

第一篇文章中我们已经添加了灯光,现在我们有背景了,为了让我们的物体在这个场景中更为的真实,那么我们需要给物体增加在光照下的阴影,那么添加光照阴影还需要下面几步

  • 材质要满足能够对光照有反应
  • 设置渲染器开启阴影的计算:renderer.shadowMap.enabled = true;
  • 设置光照投射阴影:lineLight.castShadow = true;
  • 设置物体投射阴影:mesh.castShadow = true;
  • 设置物体接收阴影:plane.receiveShadow = true; 完整代码如下
// @ts-nocheck
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

export function Tree() {
  // 创建场景
  const scene = new THREE.Scene();
  scene.fog = new THREE.Fog(0x000000, 600, 3000); //雾化场景

  const camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    1,
    1000
  );
  // 设置相机位置
  camera.position.set(10, 10, 10);
  scene.add(camera);

  // 灯光;
  // 环境光
  const light = new THREE.AmbientLight(0xa0a0a0);
  scene.add(light);
  // 直线光
  const lineLight = new THREE.DirectionalLight(0xffffff);
  lineLight.position.set(10, 10, 10);
  // 如果设置为 true 该平行光会产生动态阴影。 警告: 这样做的代价比较高而且需要一直调整到阴影看起来正确. 查看 DirectionalLightShadow 了解详细信息。该属性默认为 false
  lineLight.castShadow = true;
  lineLight.shadow.radius = 20;
  lineLight.shadow.mapSize.set(2048, 2048);
  lineLight.shadowCameraVisible = true;

  scene.add(lineLight);

  // // 导入纹理
  new THREE.TextureLoader().load(
    '/watermelon.png',
    function (texture) {
      // in this example we create the material when the texture is loaded
      const material = new THREE.MeshStandardMaterial({
        map: texture,
      });
      // 添加物体
      const cubeGeometry = new THREE.SphereGeometry(2, 32, 16);
      const cube = new THREE.Mesh(cubeGeometry, material);
      cube.castShadow = true;
      scene.add(cube);
    },

    // 目前暂不支持onProgress的回调
    undefined,
    // onError回调
    function (err) {
      console.error('An error happened.', err);
    }
  );

  // 创建平面 用于接收阴影
  const planeGeometry = new THREE.PlaneGeometry(100, 100);
  // 基础网格材质
  const material = new THREE.MeshStandardMaterial();
  const plane = new THREE.Mesh(planeGeometry, material);
  plane.position.set(0, -3, 0);
  plane.rotation.x = -Math.PI / 2;
  // 接收阴影
  plane.receiveShadow = true;
  scene.add(plane);

  // 初始化渲染器
  const renderer = new THREE.WebGLRenderer();
  // 设置渲染的尺寸大小
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 开启场景中的阴影贴图
  renderer.shadowMap.enabled = true;
  // 创建轨道控制器
  const controls = new OrbitControls(camera, renderer.domElement);
  // 为控制器设置阻尼,让控制器有真实的效果
  controls.enableDamping = true;

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

  const render = () => {
    controls.update();
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  };

  // 将webgl渲染的canvas内容添加到页面上
  const app = document.getElementById('App');
  app?.appendChild(renderer.domElement);

  // 使用渲染器,通过相机将场景渲染进来
  render();

  window.addEventListener('resize', () => {
    // 更新摄像头
    camera.aspect = window.innerWidth / window.innerHeight;
    // 更新摄像机的投影矩阵
    camera.updateProjectionMatrix();
    // 更新渲染器
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 设置渲染器的像素比
    renderer.setPixelRatio(window.devicePixelRatio);
  });
  window.addEventListener('dblclick', () => {
    const fullScreenElement = document.fullscreenElement;
    if (fullScreenElement) {
      document.exitFullscreen();
    } else {
      renderer.domElement.requestFullscreen();
    }
  });
}

在tree.js 的 DirectionalLight 介绍中可以看到下方的一条⚠️,所以还是需要根据具体的业务进行取舍 image.png 运行效果:

image.png

题外话

我们都喜欢执着于过去,可能永远也不会穿的旧衣服,占着内存却舍不得删掉的老照片,还有偶尔偶尔在无眠的夜里想起曾经的恋人,对过去美好时光的留恋,更多是因为对未来的不确定,但过去毕竟已经过去了,我们都应该试着学会告别,往前走吧,勇敢一点。