React Three Fiber 101

Alpha, Orderly·2024년 2월 3일
0

ThreeJS

목록 보기
1/2

설치

yarn add three @types/three @react-three/fiber

들어가기 앞서

  1. Three JS 는 오른손 좌표계를 사용한다.

Canvas

  • 모든 Threejs 코드에 필요한 필수사항
return (
    <>
      <Canvas>
      </Canvas>
    </>
  )
  • 빈 Canvas 예시.
return (
    <>
      <Canvas>
        <mesh>
          <boxGeometry />
        </mesh>
      </Canvas>
    </>
  )
  • 간단한 box를 추가한 예시

mesh

  • 가장 기본적인 요소
  • 여러가지 요소를 children으로 줄수 있다.
<>
      <Canvas>
        <directionalLight position={[0, 0, 2]}/>
        <ambientLight />
        <mesh position={[1, 0, 0]}>
          <boxGeometry args={[2, 2, 2]} />
          <meshStandardMaterial color={"orange"}/>
        </mesh>
      </Canvas>
    </>
  • material ( 텍스처 ) 를 적용한 예시
  • args로 x축, y축, z축 scale을 2배씩 늘렸다.
  • mesh에 position으로 위치를 이동했다.

Component

const Cube = () => {
  return (
    <mesh position={[2, 0, 0]}>
      <boxGeometry />
      <meshStandardMaterial color={"orange"}/>
    </mesh>
  )
}
  • mesh를 컴포넌트로 뺄수도 있다.

group

        <group position={[-1, 0, 0]}>
          <Cube position={[1, 0, 0]} color={"green"} size={[1, 1, 1]}/>

          <Cube position={[-1, 0, 0]} color={"hotpink"} size={[1, 1, 1]}/>

          <Cube position={[-1, 2, 0]} color={"hotpink"} size={[1, 1, 1]}/>

          <Cube position={[1, 2, 0]} color={"hotpink"} size={[1, 1, 1]}/>
        </group>
  • 여러 요소를 그룹지을수 있다.
  • group 전체의 position을 조정할수 있다.

ambientLight

  • 주변광, Canvas 안에 넣는다.
<ambientLight intensity={0.2}/>

directionalLight

  • 직접광, Canvas 안에 넣는다.
<ambientLight intensity={0.2}/>

Animation

useFrame

useFrame((state, delta, xrFrame) => {
	// state : 현재 상태
	// delta : 현재 프레임과 다음 프레임 시간 차이 ( 초 )
})
const Cube = ({position, size, color}: {position: [number, number, number], size: [number, number, number], color: string}) => {
  
  const ref = useRef<any>();

  useFrame((state, delta, frame) => {
      ref.current.rotation.x += delta
  })
  
  return (
    <mesh position={position} ref={ref}>
      <boxGeometry args={size}/>
      <meshStandardMaterial color={color}/>
    </mesh>
  )
}
  • ref 로 mesh를 가져와 delta만큼 회전하는 예시

SphereGeometry

https://threejs.org/docs/#api/en/geometries/SphereGeometry

const Sphere = ({position, args, color}: {position: [number, number, number], args: [number, number, number], color: string}) => {
  return (
    <mesh position={position}>
      <sphereGeometry args={args}/>
      <meshStandardMaterial color={color}/>
    </mesh>
  )
}

TorusGeometry

https://threejs.org/docs/#api/en/geometries/TorusGeometry

  • 도넛
const Torus = ({position, args, color}: {position: [number, number, number], args: [number, number, number, number], color: string}) => {
  return (
    <mesh position={position}>
      <torusGeometry args={args}/>
      <meshStandardMaterial color={color}/>
    </mesh>
  )
}

TorusKnotGeometry

https://threejs.org/docs/#api/en/geometries/TorusKnotGeometry

  • 꼬인 도넛

Interaction

Hover

const Sphere = ({position, args, color}: {position: [number, number, number], args: [number, number, number], color: string}) => {
  
  const ref = useRef<any>();
 
  const [isHovered, setIsHovered] = useState(false);

  useFrame((state, delta, frame) => {
      ref.current.rotation.y += delta * .2
  })
  
  return (
    <mesh position={position} ref={ref} onPointerEnter={(event) => {
      event.stopPropagation();
      setIsHovered(true);
    }} onPointerLeave={() => {
      setIsHovered(false);
    }}>
      <sphereGeometry args={args}/>
      <meshStandardMaterial color={isHovered ? "orange" : "lightblue"} wireframe/>
    </mesh>
  )
}
  • useState, onPointer 를 이용해 마우스를 올리면 색이 바뀌도록 설정한 예시.

PLUS

  • StandardMaterial
    • wireframe : 폴리곤을 그대로 보여주는 attribute

drei

  • react-three-fiber과 같이 사용하는 헬퍼 라이브러리

OrbitControls

  • 마우스로 메쉬를 움직일수 있게 된다.
  • Canvas 안에 추가하되 맨 위에 위치하도록 한다.
<Canvas>
	<OrbitControls />
...
...
</Canvas>

MeshWobbleMaterial

  • 메쉬가 젤리처럼 흐물거리게 된다.

MeshDistortMaterial

  • 메쉬가 비틀린다.

useHelper

  • 개발을 돕는다.
const directionalLightRef = useRef<any>()
useHelper(directionalLightRef, DirectionalLightHelper);
<directionalLight position={[0, 0, 2]} intensity={0.5} ref={directionalLightRef}/>
  • 위 예시는 directionalLight 를 시각화해준다.

LEVA

yarn add leva
  • 3D 메쉬를 조정할수 있는 GUI를 브라우저단에 만들어준다.
  • 앱의 최상단에 를 추가한다.
  const { lightColor, lightIntensity } = useControls({
    lightColor: 'white',
    lightIntensity: {
      value: 0.5,
      min: 0, 
      max: 5,
    },
  })
  
<directionalLight position={[0, 0, 2]} intensity={lightIntensity} ref={directionalLightRef} color={lightColor}/>
  • 이후 useControls 로 기본값을 설정하고 사용하면 된다.
  • min, max 를 설정할수도 있다.
profile
만능 컴덕후 겸 번지 팬

0개의 댓글