React Three Fiber와 3D 웹 개발
React 생태계에서 선언적으로 3D 그래픽을 개발하는 방법 마스터하기
React Three Fiber란?
Three.js를 React 방식으로 사용할 수 있게 해주는 선언적 3D 개발 라이브러리
핵심 특징
선언적 3D 개발
JSX 문법으로 3D 씬을 구성하여 직관적인 개발이 가능합니다
React 생태계 통합
hooks, context, suspense 등 React 패턴을 그대로 활용합니다
자동 리소스 관리
컴포넌트 언마운트 시 GPU 메모리가 자동으로 정리됩니다
성능 최적화 내장
React의 재조정 알고리즘으로 효율적인 렌더링을 제공합니다
Three.js vs React Three Fiber
Three.js (명령형)
// Three.js - 명령형 방식
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: "orange" });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
renderer.render(scene, camera);
}
animate();
// 정리 코드도 직접 작성해야 함
geometry.dispose();
material.dispose();React Three Fiber (선언적)
// React Three Fiber - 선언적 방식
import { Canvas, useFrame } from "@react-three/fiber";
import { useRef } from "react";
function RotatingBox() {
const meshRef = useRef();
useFrame(() => {
meshRef.current.rotation.x += 0.01;
});
return (
<mesh ref={meshRef}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="orange" />
</mesh>
);
}
function App() {
return (
<Canvas>
<ambientLight />
<RotatingBox />
</Canvas>
);
}
// 컴포넌트 언마운트 시 자동 정리!R3F의 장점 비교
| 특징 | Three.js | React Three Fiber |
|---|---|---|
| 코드 스타일 | 명령형 | 선언적 |
| 리소스 관리 | 수동 dispose | 자동 정리 |
| 상태 관리 | 직접 구현 | React 상태/Context |
| 컴포넌트 재사용 | 어려움 | 자연스러움 |
| 학습 곡선 | Three.js 전체 학습 | React 지식 활용 |
핵심 포인트
React Three Fiber는 Three.js의 모든 기능을 React 컴포넌트로 래핑하여, 기존 React 지식을 활용하면서도 강력한 3D 그래픽을 구현할 수 있게 해줍니다. 선언적 방식으로 코드 가독성이 높아지고, 자동 리소스 관리로 메모리 누수 걱정이 없습니다.
개발 환경 설정
Vite + React + TypeScript 기반의 R3F 프로젝트 구축하기
프로젝트 생성 및 설치
# Vite + React + TypeScript
npm create vite@latest my-r3f-project -- --template react-ts
cd my-r3f-project
# 핵심 의존성 설치
npm install three @react-three/fiber
# 유틸리티 라이브러리 (권장)
npm install @react-three/drei
# TypeScript 타입
npm install -D @types/three프로젝트 구조
src/ ├── components/ │ └── Scene/ │ ├── index.tsx │ ├── Lighting.tsx │ ├── Camera.tsx │ └── Models/ │ └── Box.tsx ├── hooks/ │ └── useAnimation.ts ├── App.tsx └── main.tsx
첫 번째 3D 씬
// App.tsx
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
function Box() {
return (
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="royalblue" />
</mesh>
);
}
export default function App() {
return (
<div style={{ width: "100vw", height: "100vh" }}>
<Canvas>
{/* 조명 */}
<ambientLight intensity={0.5} />
<directionalLight position={[10, 10, 5]} intensity={1} />
{/* 3D 오브젝트 */}
<Box />
{/* 카메라 컨트롤 */}
<OrbitControls />
</Canvas>
</div>
);
}개발 팁
- @react-three/drei는 R3F 개발에 필수적인 유틸리티 컴포넌트를 제공합니다
- TypeScript 타입(@types/three)을 설치하면 자동완성과 타입 안전성을 확보할 수 있습니다
- OrbitControls를 추가하면 마우스로 카메라를 조작할 수 있어 개발이 편리합니다
핵심 개념
Canvas, Geometry, Material, Lighting, Shadow의 기본 이해
Canvas 컴포넌트
Canvas는 R3F의 최상위 컴포넌트로, WebGL 렌더러, 카메라, 씬을 자동으로 설정합니다.
import { Canvas } from "@react-three/fiber";
<Canvas
// 카메라 설정
camera={{
position: [0, 0, 5],
fov: 75,
near: 0.1,
far: 1000,
}}
// 렌더러 설정
gl={{
antialias: true,
alpha: true, // 투명 배경
powerPreference: "high-performance",
}}
// 그림자 활성화
shadows
// DPR (Device Pixel Ratio)
dpr={[1, 2]}
// 프레임 루프 모드
frameloop="demand" // "always" | "demand" | "never"
>
{/* 3D 씬 내용 */}
</Canvas>Geometry와 Material
Geometry는 3D 오브젝트의 형태를, Material은 표면의 색상과 질감을 정의합니다.
// 기본 도형들
function Geometries() {
return (
<>
{/* 박스 */}
<mesh position={[-3, 0, 0]}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="red" />
</mesh>
{/* 구 */}
<mesh position={[0, 0, 0]}>
<sphereGeometry args={[0.5, 32, 32]} />
<meshStandardMaterial color="green" />
</mesh>
{/* 원기둥 */}
<mesh position={[3, 0, 0]}>
<cylinderGeometry args={[0.5, 0.5, 1, 32]} />
<meshStandardMaterial color="blue" />
</mesh>
{/* 토러스 (도넛) */}
<mesh position={[0, 2, 0]}>
<torusGeometry args={[0.5, 0.2, 16, 100]} />
<meshStandardMaterial color="purple" metalness={0.8} roughness={0.2} />
</mesh>
</>
);
}조명 시스템
function Lighting() {
return (
<>
{/* 환경광 - 모든 방향에서 균일하게 */}
<ambientLight intensity={0.3} />
{/* 방향광 - 태양처럼 평행광 */}
<directionalLight
position={[10, 10, 5]}
intensity={1}
castShadow
shadow-mapSize={[2048, 2048]}
/>
{/* 점광원 - 전구처럼 한 점에서 방사 */}
<pointLight position={[0, 5, 0]} intensity={1} color="yellow" />
{/* 스포트라이트 - 원뿔 형태 */}
<spotLight
position={[5, 5, 0]}
angle={0.3}
penumbra={0.5}
intensity={1}
castShadow
/>
</>
);
}그림자 설정
그림자 설정 포인트
shadowsCanvas 속성으로 그림자 시스템 활성화castShadow광원과 오브젝트에 그림자를 드리우도록 설정receiveShadow바닥이나 벽에 그림자를 받도록 설정
function ShadowScene() {
return (
<Canvas shadows>
{/* 그림자를 드리우는 광원 */}
<directionalLight
position={[5, 5, 5]}
castShadow
shadow-mapSize={[2048, 2048]}
shadow-camera-far={50}
shadow-camera-left={-10}
shadow-camera-right={10}
/>
{/* 그림자를 드리우는 오브젝트 */}
<mesh position={[0, 1, 0]} castShadow>
<boxGeometry />
<meshStandardMaterial />
</mesh>
{/* 그림자를 받는 바닥 */}
<mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow>
<planeGeometry args={[10, 10]} />
<meshStandardMaterial />
</mesh>
</Canvas>
);
}Hooks와 애니메이션
useFrame, useThree, useLoader를 활용한 애니메이션 구현
useFrame
렌더 루프 내에서 매 프레임 실행되는 콜백
useThree
R3F 내부 상태(camera, gl, scene 등) 접근
useLoader
텍스처, 모델 등 에셋 비동기 로딩
useFrame
useFrame은 매 프레임마다 실행되어 애니메이션을 구현합니다. delta 값으로 프레임 독립적인 애니메이션을 만들 수 있습니다.
import { useFrame } from "@react-three/fiber";
import { useRef } from "react";
import { Mesh } from "three";
function AnimatedBox() {
const meshRef = useRef<Mesh>(null);
useFrame((state, delta) => {
if (!meshRef.current) return;
// delta: 이전 프레임과의 시간 차이 (초)
meshRef.current.rotation.y += delta;
// state: R3F 상태 객체
// state.clock - Three.js Clock
// state.camera - 현재 카메라
// state.gl - WebGL 렌더러
// state.scene - Three.js Scene
// state.mouse - 정규화된 마우스 좌표 (-1 ~ 1)
// 시간 기반 애니메이션
meshRef.current.position.y = Math.sin(state.clock.elapsedTime) * 0.5;
});
return (
<mesh ref={meshRef}>
<boxGeometry />
<meshStandardMaterial color="orange" />
</mesh>
);
}useThree
useThree는 R3F의 내부 상태에 접근하여 카메라, 렌더러, 씬 등을 조작할 수 있게 해줍니다.
import { useThree } from "@react-three/fiber";
function CameraInfo() {
const { camera, gl, scene, size, viewport } = useThree();
console.log("Canvas 크기:", size.width, size.height);
console.log("Viewport:", viewport.width, viewport.height);
console.log("카메라 위치:", camera.position);
return null;
}
// 특정 값만 구독 (성능 최적화)
function OptimizedComponent() {
const camera = useThree((state) => state.camera);
// camera가 변경될 때만 리렌더링
return null;
}useLoader
useLoader는 Three.js의 로더를 React Suspense와 통합하여 텍스처나 3D 모델을 로딩합니다.
import { useLoader } from "@react-three/fiber";
import { TextureLoader } from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { Suspense } from "react";
// 텍스처 로딩
function TexturedBox() {
const texture = useLoader(TextureLoader, "/textures/wood.jpg");
return (
<mesh>
<boxGeometry />
<meshStandardMaterial map={texture} />
</mesh>
);
}
// GLTF 모델 로딩
function Model() {
const gltf = useLoader(GLTFLoader, "/models/robot.glb");
return <primitive object={gltf.scene} />;
}
// Suspense와 함께 사용
function Scene() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Model />
</Suspense>
);
}커스텀 애니메이션 훅
import { useFrame } from "@react-three/fiber";
import { useRef, useState } from "react";
import { MathUtils } from "three";
// 부드러운 값 변화
function useSmoothValue(target: number, smoothness = 0.1) {
const current = useRef(target);
useFrame(() => {
current.current = MathUtils.lerp(current.current, target, smoothness);
});
return current;
}
// 사용 예시
function SmoothBox() {
const [hovered, setHovered] = useState(false);
const scale = useSmoothValue(hovered ? 1.5 : 1, 0.1);
return (
<mesh
onPointerOver={() => setHovered(true)}
onPointerOut={() => setHovered(false)}
scale={scale.current}
>
<boxGeometry />
<meshStandardMaterial color={hovered ? "hotpink" : "royalblue"} />
</mesh>
);
}애니메이션 팁
- delta 값을 사용하면 프레임 레이트에 상관없이 일정한 속도의 애니메이션을 구현할 수 있습니다
- useThree에서 특정 값만 구독하면 불필요한 리렌더링을 방지할 수 있습니다
- 무거운 계산은 useMemo로 캐싱하여 성능을 최적화하세요
@react-three/drei 유틸리티
카메라 컨트롤, 환경, 텍스트, 모델 로딩 등 필수 유틸리티
카메라 컨트롤
import {
OrbitControls,
PerspectiveCamera,
CameraShake,
} from "@react-three/drei";
function CameraSetup() {
return (
<>
{/* 궤도 카메라 컨트롤 */}
<OrbitControls
enablePan={true}
enableZoom={true}
enableRotate={true}
minDistance={2}
maxDistance={20}
minPolarAngle={0}
maxPolarAngle={Math.PI / 2}
/>
{/* 카메라 흔들림 효과 */}
<CameraShake
intensity={0.5}
decay
decayRate={0.65}
/>
</>
);
}환경과 조명
import { Environment, Sky, Stars } from "@react-three/drei";
function EnvironmentSetup() {
return (
<>
{/* HDRI 환경 맵 */}
<Environment
preset="sunset" // city, sunset, dawn, night, warehouse, forest, apartment, studio, park, lobby
background
/>
{/* 또는 커스텀 HDRI */}
<Environment files="/hdri/studio.hdr" />
{/* 하늘 */}
<Sky sunPosition={[100, 20, 100]} />
{/* 별 */}
<Stars radius={100} depth={50} count={5000} factor={4} />
</>
);
}Environment 프리셋
city, sunset, dawn, night, warehouse, forest, apartment, studio, park, lobby 등의 프리셋을 사용하거나 커스텀 HDRI를 적용할 수 있습니다.
헬퍼와 디버깅
import {
Grid,
GizmoHelper,
GizmoViewport,
Stats,
} from "@react-three/drei";
function DebugHelpers() {
return (
<>
{/* 그리드 */}
<Grid
args={[10, 10]}
cellSize={0.5}
cellColor="gray"
sectionSize={2}
sectionColor="white"
fadeDistance={25}
infiniteGrid
/>
{/* 축 표시 */}
<axesHelper args={[5]} />
{/* 뷰포트 기즈모 */}
<GizmoHelper alignment="bottom-right" margin={[80, 80]}>
<GizmoViewport />
</GizmoHelper>
{/* FPS 카운터 */}
<Stats />
</>
);
}텍스트와 HTML
import { Text, Text3D, Html, Billboard } from "@react-three/drei";
function TextElements() {
return (
<>
{/* 2D 텍스트 (빌보드) */}
<Text
position={[0, 2, 0]}
fontSize={0.5}
color="white"
anchorX="center"
anchorY="middle"
>
Hello R3F!
</Text>
{/* 3D 텍스트 */}
<Text3D
font="/fonts/helvetiker_regular.typeface.json"
size={0.5}
height={0.2}
>
3D Text
<meshStandardMaterial color="gold" />
</Text3D>
{/* HTML 오버레이 */}
<mesh position={[2, 0, 0]}>
<boxGeometry />
<meshStandardMaterial />
<Html distanceFactor={10} position={[0, 1, 0]}>
<div className="annotation">제품 정보</div>
</Html>
</mesh>
</>
);
}모델 로딩
import { useGLTF, Clone } from "@react-three/drei";
// GLTF 모델
function Robot() {
const { scene, nodes, materials } = useGLTF("/models/robot.glb");
return <primitive object={scene} scale={0.5} />;
}
// 모델 프리로드 (성능 최적화)
useGLTF.preload("/models/robot.glb");
// 모델 복제
function MultipleRobots() {
const { scene } = useGLTF("/models/robot.glb");
return (
<>
<Clone object={scene} position={[-2, 0, 0]} />
<Clone object={scene} position={[0, 0, 0]} />
<Clone object={scene} position={[2, 0, 0]} />
</>
);
}Drei 활용 팁
Drei의 useGLTF.preload를 사용하면 모델을 미리 로드하여 첫 렌더링 시 지연을 줄일 수 있습니다. Clone 컴포넌트로 같은 모델을 여러 번 효율적으로 렌더링하세요.
인터랙션
포인터 이벤트, 드래그 앤 드롭, 레이캐스팅
포인터 이벤트
import { useState } from "react";
function InteractiveBox() {
const [hovered, setHovered] = useState(false);
const [clicked, setClicked] = useState(false);
return (
<mesh
onPointerOver={(e) => {
e.stopPropagation();
setHovered(true);
document.body.style.cursor = "pointer";
}}
onPointerOut={(e) => {
setHovered(false);
document.body.style.cursor = "auto";
}}
onClick={(e) => {
e.stopPropagation();
setClicked(!clicked);
}}
onDoubleClick={(e) => console.log("더블 클릭!")}
onPointerDown={(e) => console.log("포인터 다운")}
onPointerUp={(e) => console.log("포인터 업")}
onPointerMove={(e) => {
// e.point - 3D 월드 좌표
// e.uv - UV 좌표
// e.face - 충돌한 면
// e.distance - 카메라와의 거리
}}
scale={clicked ? 1.5 : 1}
>
<boxGeometry />
<meshStandardMaterial color={hovered ? "hotpink" : "royalblue"} />
</mesh>
);
}드래그 & 드롭
import { useDrag } from "@use-gesture/react";
import { useSpring, animated } from "@react-spring/three";
function DraggableBox() {
const [spring, api] = useSpring(() => ({
position: [0, 0, 0],
config: { mass: 1, tension: 170, friction: 26 },
}));
const bind = useDrag(({ offset: [x, y] }) => {
api.start({ position: [x / 100, -y / 100, 0] });
});
return (
<animated.mesh {...spring} {...bind()}>
<boxGeometry />
<meshStandardMaterial color="coral" />
</animated.mesh>
);
}라이브러리 조합
@use-gesture/react로 제스처를 감지하고, @react-spring/three로 부드러운 애니메이션을 적용합니다.
Raycasting (광선 투사)
import { useThree } from "@react-three/fiber";
import { Raycaster, Vector2 } from "three";
import { useEffect } from "react";
function RaycastExample() {
const { camera, scene, gl } = useThree();
const raycaster = new Raycaster();
const mouse = new Vector2();
useEffect(() => {
const handleClick = (event: MouseEvent) => {
// 마우스 좌표를 정규화 (-1 ~ 1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// 레이캐스트 수행
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length > 0) {
const hit = intersects[0];
console.log("충돌 오브젝트:", hit.object);
console.log("충돌 지점:", hit.point);
console.log("거리:", hit.distance);
}
};
gl.domElement.addEventListener("click", handleClick);
return () => gl.domElement.removeEventListener("click", handleClick);
}, [camera, scene, gl]);
return null;
}인터랙션 팁
e.stopPropagation()를 사용하여 이벤트 버블링을 방지하세요- document.body.style.cursor를 변경하여 커서를 직접 제어하세요
- e.point로 3D 공간에서의 정확한 클릭 위치를 얻을 수 있습니다
성능 최적화
인스턴싱, 프레임 제어, 메모리 관리, 모니터링
인스턴싱 (InstancedMesh)
동일한 geometry와 material을 가진 수천 개의 오브젝트를 단일 드로우 콜로 렌더링하여 성능을 크게 향상시킵니다.
import { useFrame } from "@react-three/fiber";
import { useMemo, useRef } from "react";
import { InstancedMesh, Object3D } from "three";
// 인스턴싱 - 동일 오브젝트 대량 렌더링
function Particles({ count = 1000 }) {
const meshRef = useRef<InstancedMesh>(null);
const dummy = useMemo(() => new Object3D(), []);
// 초기 위치 설정
useMemo(() => {
if (!meshRef.current) return;
for (let i = 0; i < count; i++) {
dummy.position.set(
Math.random() * 20 - 10,
Math.random() * 20 - 10,
Math.random() * 20 - 10
);
dummy.updateMatrix();
meshRef.current.setMatrixAt(i, dummy.matrix);
}
meshRef.current.instanceMatrix.needsUpdate = true;
}, [count]);
return (
<instancedMesh ref={meshRef} args={[undefined, undefined, count]}>
<sphereGeometry args={[0.1, 8, 8]} />
<meshStandardMaterial color="white" />
</instancedMesh>
);
}프레임 루프 제어
Canvas의 frameloop 속성으로 렌더링 빈도를 제어하여 불필요한 리렌더링을 방지합니다.
// Canvas에서 프레임 제어
<Canvas frameloop="demand">
{/* invalidate()를 통해 수동으로 렌더링 요청 */}
</Canvas>
// 컴포넌트에서 프레임 제어
function ControlledAnimation() {
const { invalidate } = useThree();
useFrame((state, delta) => {
// 필요할 때만 렌더링 요청
if (needsUpdate) {
invalidate();
}
}, 1); // 우선순위 설정 (숫자가 낮을수록 먼저 실행)
return null;
}메모리 관리
R3F는 컴포넌트 언마운트 시 자동으로 리소스를 정리하지만, 커스텀 정리가 필요한 경우도 있습니다.
import { useEffect } from "react";
import { useThree } from "@react-three/fiber";
function MemoryCleanup() {
const { gl, scene } = useThree();
useEffect(() => {
return () => {
// 씬 정리
scene.traverse((object) => {
if ("geometry" in object) {
(object as any).geometry?.dispose();
}
if ("material" in object) {
const material = (object as any).material;
if (Array.isArray(material)) {
material.forEach((m) => m.dispose());
} else {
material?.dispose();
}
}
});
// 렌더러 정리
gl.dispose();
};
}, [gl, scene]);
return null;
}성능 모니터링
import { Perf } from "r3f-perf";
import { Stats } from "@react-three/drei";
function PerformanceMonitor() {
return (
<>
{/* 상세 성능 정보 */}
<Perf
position="top-left"
showGraph
minimal={false}
matrixUpdate={true}
deepAnalyze={true}
/>
{/* 간단한 FPS 표시 */}
<Stats showPanel={0} className="stats" />
</>
);
}성능 최적화 체크리스트
- 동일 오브젝트 대량 렌더링 시 InstancedMesh 사용
- 정적인 씬에서는 frameloop="demand" 설정
- useThree에서 필요한 상태만 구독하여 리렌더링 최소화
- 무거운 계산은 useMemo로 캐싱
- 텍스처 해상도 최적화 및 압축 포맷 사용
- 복잡한 모델은 LOD(Level of Detail) 적용
고급 기법
포스트 프로세싱, 셰이더, 물리 엔진, VR/AR
포스트 프로세싱
@react-three/postprocessing으로 블룸, 색수차, 비네트 등 다양한 후처리 효과를 적용할 수 있습니다.
import {
EffectComposer,
Bloom,
ChromaticAberration,
Vignette,
DepthOfField,
SMAA,
} from "@react-three/postprocessing";
import { BlendFunction } from "postprocessing";
function PostEffects() {
return (
<EffectComposer>
{/* 블룸 효과 (빛 번짐) */}
<Bloom
luminanceThreshold={0.9}
luminanceSmoothing={0.025}
intensity={0.5}
/>
{/* 색수차 */}
<ChromaticAberration
offset={[0.002, 0.002]}
blendFunction={BlendFunction.NORMAL}
/>
{/* 비네트 (가장자리 어두움) */}
<Vignette eskil={false} offset={0.1} darkness={0.5} />
{/* 피사계 심도 */}
<DepthOfField
focusDistance={0}
focalLength={0.02}
bokehScale={2}
/>
{/* 안티앨리어싱 */}
<SMAA />
</EffectComposer>
);
}커스텀 셰이더 (GLSL)
shaderMaterial을 사용하여 커스텀 버텍스/프래그먼트 셰이더를 작성할 수 있습니다.
import { shaderMaterial } from "@react-three/drei";
import { extend, useFrame } from "@react-three/fiber";
import { useRef } from "react";
// 커스텀 셰이더 머티리얼 정의
const WaveMaterial = shaderMaterial(
// Uniforms
{ uTime: 0, uColor: [1.0, 0.0, 0.0] },
// Vertex Shader
`
uniform float uTime;
varying vec2 vUv;
void main() {
vUv = uv;
vec3 pos = position;
pos.z += sin(pos.x * 5.0 + uTime) * 0.1;
pos.z += cos(pos.y * 5.0 + uTime) * 0.1;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
// Fragment Shader
`
uniform vec3 uColor;
varying vec2 vUv;
void main() {
gl_FragColor = vec4(uColor * vUv.x, 1.0);
}
`
);
extend({ WaveMaterial });
function WavePlane() {
const materialRef = useRef<any>(null);
useFrame((state) => {
if (materialRef.current) {
materialRef.current.uTime = state.clock.elapsedTime;
}
});
return (
<mesh rotation={[-Math.PI / 4, 0, 0]}>
<planeGeometry args={[5, 5, 32, 32]} />
<waveMaterial ref={materialRef} uColor={[0.2, 0.5, 1.0]} />
</mesh>
);
}셰이더 학습 자료
GLSL 셰이더를 처음 접한다면 The Book of Shaders(thebookofshaders.com)를 추천합니다.
물리 엔진 (Rapier)
@react-three/rapier를 사용하면 중력, 충돌, 탄성 등 현실적인 물리 시뮬레이션을 적용할 수 있습니다.
import { Physics, RigidBody, CuboidCollider } from "@react-three/rapier";
function PhysicsScene() {
return (
<Physics gravity={[0, -9.81, 0]} debug>
{/* 동적 물체 */}
<RigidBody position={[0, 5, 0]} restitution={0.5}>
<mesh>
<sphereGeometry args={[0.5]} />
<meshStandardMaterial color="red" />
</mesh>
</RigidBody>
{/* 여러 개의 박스 */}
{Array.from({ length: 10 }).map((_, i) => (
<RigidBody
key={i}
position={[Math.random() * 4 - 2, 10 + i * 2, Math.random() * 4 - 2]}
>
<mesh>
<boxGeometry />
<meshStandardMaterial color="orange" />
</mesh>
</RigidBody>
))}
{/* 정적 바닥 */}
<RigidBody type="fixed">
<CuboidCollider args={[10, 0.5, 10]} />
<mesh position={[0, -0.5, 0]}>
<boxGeometry args={[20, 1, 20]} />
<meshStandardMaterial color="lightgray" />
</mesh>
</RigidBody>
</Physics>
);
}XR (VR/AR)
@react-three/xr로 WebXR 기반의 VR/AR 경험을 React 컴포넌트로 구현할 수 있습니다.
import { XR, Controllers, Hands, VRButton } from "@react-three/xr";
function VRScene() {
return (
<>
<VRButton />
<Canvas>
<XR>
<Controllers />
<Hands />
{/* VR 환경 */}
<Environment preset="sunset" background />
{/* VR에서 상호작용 가능한 오브젝트 */}
<Interactive onSelect={() => console.log("선택됨!")}>
<mesh position={[0, 1, -2]}>
<boxGeometry />
<meshStandardMaterial color="blue" />
</mesh>
</Interactive>
</XR>
</Canvas>
</>
);
}