Hola, tengo un componente Cube simple hecho con fibra de reacción tres .
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;Estoy importando el componente Box en App.js y usándolo de esta manera:
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;En este momento puedo hacer clic en el cubo y ejecuta la función boxClick correctamente. Lo que quiero asignar es una función de clic diferente a cada cara del cubo.
Puedes dibujar seis planos y cambiar la rotación o la posición cada vez para construir un cubo.
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> );};
Y luego agrégalos a tu escena.
<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>