0

我目前是新手,正在学习three.js。我react-three-fiber用 React 来实现它,但我偶然发现了一个问题。它不能给模型投下任何阴影。我也尝试obj.castShadow = true在父母和孩子身上使用,但没有区别。

这是我的沙盒链接:
https ://codesandbox.io/s/sleepy-satoshi-8eckc?file=/src/components/Model.js

任何帮助,将不胜感激。谢谢你。

4

1 回答 1

0

经过实验,结果是我不小心把它设置shadow-camera-far为 50。我的错。

所以这就是我的最终代码的样子

const PerspectiveCamera = (props) => {
  const cam = useRef();
  const { setDefaultCamera } = useThree();
  useFrame(() => cam.current.updateMatrixWorld());
  useHelper(cam, CameraHelper, 1, "hotpink");

  return <perspectiveCamera ref={cam} {...props} />;
};

const Model = ({ modelPath }) => {
  const [obj, setObj] = useState();
  useMemo(() => new OBJLoader().load(modelPath, setObj), [modelPath]);
  if (obj) {
    obj.castShadow = true;
    obj.traverse((children) => {
      if (children instanceof Mesh) {
        children.castShadow = true;
      }
    });
  }
  return obj ? <primitive object={obj} /> : null;
};

const Lights = () => {
  const refLight1 = useRef();
  const refLight2 = useRef();
  const refLight3 = useRef();
  useHelper(refLight1, PointLightHelper, 5);
  useHelper(refLight2, PointLightHelper, 5);
  useHelper(refLight3, DirectionalLightHelper, 5);

  return (
    <>
      <ambientLight intensity={0.1} />
      <directionalLight
        ref={refLight3}
        castShadow
        position={[50, 20, 80]}
        intensity={0.5}
        shadow-mapSize-shadowMapWidth={2048}
        shadow-mapSize-shadowMapHeight={2048}
        shadow-camera-left={-10}
        shadow-camera-right={10}
        shadow-camera-top={-50}
        shadow-camera-bottom={10}
      />
      <pointLight ref={refLight1} position={[10, -10, -20]} intensity={0.3} />
      <pointLight ref={refLight2} position={[0, 10, 5]} intensity={0.3} />
      <spotLight intensity={1} position={[0, 1000, 0]} />
    </>
  );
};

const Billboard = () => {
  return (
    <mesh
      castShadow
      position={[-18, 5, -35]}
      scale={[0.05, 0.05, 0.05]}
      rotation={[0, 8, 0]}
    >
      <Model modelPath={billboard} />
    </mesh>
  );
};

const Shadow = () => {
  return (
    <group>
      <mesh
        receiveShadow
        rotation={[-Math.PI / 2, 0, 0]}
        position={[-20, -32, -40]}
      >
        <planeBufferGeometry attach="geometry" args={[500, 500]} />
        <meshLambertMaterial attach="material" color={"lightblue"} />
      </mesh>
    </group>
  );
};

const MegatronModel = () => {
  return (
    <>
      <Canvas
        shadowMap
        colorManagement
        camera={{ position: [-150, 5, 0], fov: 60 }}
      >
        <PerspectiveCamera position={[-10, 5, 40]} fov={60} />
        <OrbitControls
          enablePan={Boolean("Pan", true)}
          enableZoom={Boolean("Zoom", true)}
          enableRotate={Boolean("Rotate", true)}
        />
        <axesHelper />
        <Shadow />
        <Billboard />
        <Lights />
      </Canvas>
    </>
  );
};

export default MegatronModel;

于 2020-11-13T06:59:39.207 回答