@react-three/fiber:如何为阴影相机创建一个辅助程序?

6

所以我习惯这样设置帮助程序:

useHelper(sLightRef, THREE.SpotLightHelper);

return <spotLight
        castShadow
        ref={sLightRef}
        position={[0, 2, 2]}
        args={["#fff", 0.4, 10, Math.PI * 0.3]}
        ></spotLight>

这将在SpotLight对象上创建一个助手。

我不明白的是如何在SpotLight的阴影相机上创建一个助手。(spotlight.shadow.camera) 我们无法给它赋值 ref(),因为它不在我的return语句中。它是在SpotLight组件内部创建的。

在普通的Three.js中,这很容易实现:

const helper = new THREE.CameraHelper(spotlight.shadow.camera);
scene.add(helper);

我该如何在react-three-fiber中处理这个问题?我是否忽略了什么显而易见的东西?谢谢。
2个回答

7

我尝试过一些方法,但是没有找到一个简洁的解决方案。因此,我自己编写了一个类似于 useHelper 钩子的钩子。

// Components==============
import { useFrame, useThree } from '@react-three/fiber';
import React, { useRef } from 'react';
import { CameraHelper, Light } from 'three';
// =========================

export default function useShadowHelper(
  ref: React.MutableRefObject<Light | undefined>
) {
  const helper = useRef<CameraHelper>();
  const scene = useThree((state) => state.scene);

  React.useEffect(() => {
    if (!ref.current) return;

    helper.current = new CameraHelper(ref.current?.shadow.camera);
    if (helper.current) {
      scene.add(helper.current);
    }

    return () => {
      if (helper.current) {
        scene.remove(helper.current);
      }
    };
  }, [helper.current?.uuid, ref.current]);

  useFrame(() => {
    if (helper.current?.update) {
      helper.current.update();
    }
  });
}

2

您可以通过将自己的透视相机附加到聚光灯上来实现这一点。

useHelper(sLightRef, THREE.SpotLightHelper);
useHelper(shadowCameraRef, THREE.CameraHelper);

return <spotLight
        castShadow
        ref={sLightRef}
        position={[0, 2, 2]}
        args={["#fff", 0.4, 10, Math.PI * 0.3]}
       >
         <perspectiveCamera ref={shadowCameraRef} attach="shadow-camera" />
       </spotLight>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接