Learning/Three

Three.js 시작하기 06 _모델링 파일 불러오기 (.glb 파일)

Soozinyy 2024. 1. 14. 20:44

.glb 파일을 불러오기 위해서 GLTFLoader를 활용한다.

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";

// ( 이하 생략 )

// GLTF 파일 업로드
const gltfLoader = new GLTFLoader();
// gltfLoader.load("/dancer.glb", (gltf) => {
//   const charactor = gltf.scene;
//   charactor.position.y = 0.8;
//   charactor.scale.set(0.01, 0.01, 0.01);
//   scene.add(charactor);
// });

// 비동기
const gltf = await gltfLoader.loadAsync("/dancer.glb");
const charactor = gltf.scene;
charactor.position.y = 0.8;
charactor.scale.set(0.01, 0.01, 0.01);
charactor.castShadow = true;
charactor.receiveShadow = true;
// 캐릭터의 children을 계속 타고 내려가 속성을 적용해야할 때 traverse 사용
charactor.traverse((obj) => {
  if (obj.isMesh) {
    obj.castShadow = true;
    obj.receiveShadow = true;
  }
});
scene.add(charactor);

 

보통 castShadow 속성을 true로 하면 그림자가 생기지만 모델링 파일의 경우 하나의 그룹으로 이루어져 있기 때문에 children 요소들도 모두 Shadow 속성을 true로 적용시켜줄 필요가 있다.

 

이것을 한번에 처리할 수 있는 traverse를 활용한다.