괴발개발 성장기

Study/React

[Three.js] 클릭하면 모형이 바뀐다

지니유 2024. 5. 23. 15:59
반응형

 

 

 

 

배경

실무에서 적용할 때에는 클릭을 하면 무언가가 나오게 해야 효과적이라고 생각이 들었다.

그래서 이벤트를 적용시켜봤다.

 

상황

구를 클릭하면 육면체로 변경하고

육면체를 클릭하면 구로 변경된다.

 

const Sphere = ({onClick}) => {
    return (
        <>
            <OrbitControls/>
            <ambientLight intensity={0.75}/>
            <directionalLight color="white" position={[10, 10, 10]}/>
            <mesh rotation={[Math.PI / 180 * 30, 20, 0]} onClick={onClick}>
                <boxGeometry args={[3, 3, 3]}/>
                <meshStandardMaterial color="pink"/>
            </mesh>
        </>
    );
};

 

 

- Sphere 컴포넌트에 onClick이라는 props를 받아들입니다.

- Sphere 컴포넌트는 핑크색 육면체이다.

 

const Circle = ({ onClick }) => {
    const circleRef = useRef();

    useFrame(() => {
        circleRef.current.rotation.y += 0.003; // y축을 기준으로 회전
        circleRef.current.rotation.x += 0.005; // x축을 기준으로 회전
    });
    return (
        <>
            <group ref={circleRef}>
                <OrbitControls/>
                <ambientLight intensity={0.25}/>
                <directionalLight color="white" position={[10, 10, 10]}/>
                <mesh onClick={onClick} >
                    <sphereGeometry args={[1, 32, 32]}/>
                    <meshStandardMaterial color="yellow"/>
                </mesh>
            </group>
        </>
    );
};

 

- Circle 컴포넌트에 onClick이라는 props를 받아들입니다.

- 구형을 클릭하면 이벤트가 실행된다.

 

const Model = () => {
    const [visible, setVisible] = useState(false);
    return (
        <>
            <div style={{display: "flex"}}>
                <Canvas style={{width: "400px", height: "400px", background: "red"}} >
                    {!visible && <Circle onClick={() => {
                        setVisible(true)
                    }}/>}
                    {visible && (<Sphere onClick={()=>{
                        setVisible(false)
                    }
                    }/>)}
                </Canvas>
            </div>
        </>

    );
};

 

- 원을 클릭하면 setVisible에 ture를 넣으면 visible 값이 ture라서 정육면체가 보인다.

- 정육면체를 클릭하면 setVisible에 false 값을 넣으면 visible 값이 false라서 정육면체가 보인다.

 

 

 

 

# 참조 이슈

https://github.com/YooGenie/react-study/issues/53

 

클릭하면 모형이 바뀐다 · Issue #53 · YooGenie/react-study

 

github.com

 

반응형