React-fiber-三个投射阴影不起作用

时间:2021-06-27 10:42:28

标签: reactjs three.js react-three-fiber

我是 three.js@react-fiber/three 的新手,我创建了一个带有 3 个平面的简单盒子,使用了聚光灯。我试图在飞机上投射盒子的阴影,但它不起作用。

让我向您展示我的代码:

Test.js

以下代码在App.js中导入

import React from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import Scene from "./Scenes/Scene";

const Test = () => {
  return (
    <Canvas
      colorManagement
      shadowMap
      camera={{ position: [15, 15, 15], fov: 60 }}
    >
      {/* <ambientLight color="#ffffff" intensity={0.1} /> */}
      <spotLight
        position={[2, 5, 2]}
        color="#ffffff"
        intensity={2.5}
        shadow-mapSize-height={1024}
        shadow-mapSize-width={1024}
        shadow-camera-far={50}
        shadow-camera-left={-10}
        shadow-camera-right={10}
        shadow-camera-top={10}
        shadow-camera-bottom={-10}
        castShadow
      />

      <Scene />
      <OrbitControls enablePan={true} enableZoom={true} enableRotate={true} />
    </Canvas>
  );
};

export default Test;

src/Scenes/ 中的Scene.js

下面的代码是在Test.js中导入的(上)


import React, { useRef } from "react";
import { useFrame } from "@react-three/fiber";
import { Box, Plane } from "@react-three/drei";

const Scene = () => {
  const boxRef = useRef();
  useFrame(() => {
    boxRef.current.rotation.y += 0.001;
    boxRef.current.rotation.x += 0.001;
    boxRef.current.rotation.z += 0.001;
  });
  return (
    <group>
      <Box
        ref={boxRef}
        castShadow
        receiveShadow
        position={[0, 0.5, 0]}
        args={[3, 3, 3]}
      >
        <meshStandardMaterial attach="material" color="#C42727" />
      </Box>

      <Plane
        receiveShadow
        rotation={[-Math.PI / 2, 0, 0]}
        position={[0, -2, 0]}
        args={[15, 15]}
      >
        <meshPhongMaterial attach="material" color="#ffffff" />
      </Plane>

      <Plane
        receiveShadow
        rotation={[0, 0, 0]}
        position={[0, 5.5, -7.5]}
        args={[15, 15]}
      >
        <meshPhongMaterial attach="material" color="#ffffff" />
      </Plane>

      <Plane
        receiveShadow
        rotation={[0, Math.PI / 2, 0]}
        position={[-7.5, 5.5, 0]}
        args={[15, 15]}
      >
        <meshPhongMaterial attach="material" color="#ffffff" />
      </Plane>
    </group>
  );
};

export default Scene;

如您所见,我已将 castShadow 添加到以下内容中:

  • 聚光灯
  • 盒子

并接收到位面的阴影。

令我惊讶的是,它仍然不起作用。

2 个答案:

答案 0 :(得分:1)

使用meshStandardMaterial 代替您的飞机使用meshPhongMaterial,它将解决问题。您可以在此处查看现场示例Preview of app

答案 1 :(得分:0)

从 react-three-fiber (@react-three/fiber) 中发现 Canvas 组件的属性:shadowMaps 没有按预期工作,但经过研究(又名谷歌搜索)我发现了这一点video

<Canvas
    shadows
>
</Canvas>

shadows 属性是我所缺少的。