如何在反应三纤维中为立方体的每个面分配不同的点击功能



嗨,我有一个简单的立方体组件,由反应三根纤维制成。

import {useState,useRef} from 'react';
import { useFrame } from '@react-three/fiber';
const Box = ({props}) =>{
const ref = useRef()
const [hovered, hover] = useState(false)

const boxClick = () =>{
alert('clicked the object')
}
return ( 
<mesh
{...props}
ref={ref}
onClick={boxClick}
scale={2}
onPointerOver={(event) => hover(true)}
onPointerOut={(event) => hover(false)}>
<boxGeometry args={[1.5, 1.5, 1.5]} />
<meshStandardMaterial color={hovered ? 'yellow' : 'orange'} />
</mesh>
)
}
export default Box;

我正在App.js中导入Box组件,并以这种方式使用它-

function App() {
const [boxes,setBoxes] = useState(0);
const box1Click = () =>{
setBoxes(() =>boxes+1)
alert(boxes)
}
return (
<Canvas className='main-canvas'>
<ambientLight intensity={0.5} />
<spotLight position={[5, 155, 10]} angle={0.15} penumbra={1} />
<pointLight position={[-100, -200, -100]} />
<Box position = {[0 ,0,0]}  />  
</Canvas>
);
}
export default App;

现在我可以单击多维数据集,它将正确运行boxClick函数。我想给立方体的每个面分配不同的点击功能。

您可以绘制六个平面,每次都可以更改旋转或位置来构造立方体。。

const Plane = (props) => {
const ref = useRef();
const texture = useLoader(THREE.TextureLoader, "/images/wood.png");
useFrame((state) => {
if (props.rotateX) ref.current.rotation.x = props.rotateX;
if (props.rotateY) ref.current.rotation.y = props.rotateY;
if (props.rotateZ) ref.current.rotation.z = props.rotateZ;
// ref.current.rotation.x += 0.01;
// ref.current.rotation.y += 0.01;
});
return (
<mesh ref={ref} {...props}>
<planeGeometry />
<meshBasicMaterial
color="red"
side={THREE.DoubleSide}
opacity={props.opacity}
transparent
visible={props.visible}
map={texture}
/>
</mesh>
);

};

然后将它们添加到您的场景

<Suspense fallback={null}>
<Box position={[3, 3, 0]} />
<Plane
args={[2, 2]}
position={[0.5, 0, 0.5]}
rotateX={Math.PI / 2}
opacity="0.5"
visible={true}
/>
<Plane
args={[2, 2]}
position={[0.5, 0.5, 1]}
opacity="0.8"
visible={true}
/>
<Plane
args={[2, 2]}
position={[0, 0.5, 0.5]}
rotateY={Math.PI / 2}
opacity="1"
visible={true}
/>
{/** ... */}
</Suspense>

最新更新