Geometry
1. 기본 geometry
three.js 에서 기본적으로 제공하는 geometry를 살펴보겠다
이 geometry들은 기본적으로 bufferGeometry를 상속받는다
Geometry들은 3차원 오브젝트의 형상을 정의한다고했는데
geometry들의 형상을 정의하기 위한 데이터들은 다음과 같다
- 형상을 정의하는 정점(Vertex)데이터(x y z축에 대한 좌표)
- 3차원 오브젝트의 면을 구성하는 정점에 대한 인덱스
- 정점에 대한 수직벡터
- 정점에 대한 색상
- 텍스쳐 맵핑을 위한 UV 좌표
- 사용자가 정의한 데이터
이러한 데이터들은 3차원으로 시각화 될 때 GPU에 한번에 전달되어 빠르게 처리된다
이제 geometry에 대한 코드를 살펴보자
2. 코드
https://jwinjection.tistory.com/category/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D/ThreeJS
'프로그래밍/ThreeJS' 카테고리의 글 목록
jwinjection.tistory.com
이전 글에서 생성한 파일 3개를 복사해주고 이름 변경한다
html을 아래와 같이 변경해준다
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="02-geometry.css" />
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js"
}
}
</script>
<script type="module" src="02-geometry.js" defer></script>
<!-- defer는 dom이다 로드된 이후에 실행 -->
</head>
<body>
<div id="webgl-container"></div>
</body>
</html>
그리고 js파일에 _setupModel() 을 아래와 같이 변경해준다
_setupModel() {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const fillMaterial = new THREE.MeshPhongMaterial({ color: 0x515151 });
const cube = new THREE.Mesh(geometry, fillMaterial);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffff00 });
const line = new THREE.LineSegments(
new THREE.WireframeGeometry(geometry),
lineMaterial
);
const group = new THREE.Group();
group.add(cube);
group.add(line);
this._scene.add(group);
this._cube = group;
}
그럼 아래와 같이 출력되는 것을 볼 수 있다.
코드를 자세히 살펴보자
가로세로높이가 1인 box형태의 geometry를 정해주고
회색 색깔의 재질을 정의한다음
이를 이용해 cube Mesh를 생성한다
const geometry = new THREE.BoxGeometry(1, 1, 1);
const fillMaterial = new THREE.MeshPhongMaterial({ color: 0x515151 });
const cube = new THREE.Mesh(geometry, fillMaterial);
그리고 노란색의 선에대한 재질을 만들고
이 재질과 앞서만든 geometry를 이용해서 line타입의 오브젝트를 만들어준다
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffff00 });
const line = new THREE.LineSegments(
new THREE.WireframeGeometry(geometry),lineMaterial);
Mesh오브젝트와 Line오브젝트를 하나의 오브젝트로 다루기 위해서
그룹으로 묶는다
const group = new THREE.Group();
group.add(cube);
group.add(line);
scene에 추가한다
this._scene.add(group);
이 그룹을 다른 메소드에서도 사용할 수 있게
cube 필드를 생성해준다.
this._cube = group;
그룹에 대해 좀더 살펴보자면
만약 line 을 주석처리하면 어떻게 될까?
const group = new THREE.Group();
group.add(cube);
//group.add(line);
라인이 없어졌다
그렇다면 cube를 주석처리하면 어떻게 될까?
const group = new THREE.Group();
//group.add(cube);
group.add(line);
라인만 남는것을 볼 수 있다
또한 LineSegmetns를 생성할때 geometry로 WireframeGeometry를 넣어주었는데
이 geometry는 geometry를 와이어프레임 형태로 표현하기위해 사용되어진다
만약 적용하지 않는다면
const geometry = new THREE.BoxGeometry(1, 1, 1);
const fillMaterial = new THREE.MeshPhongMaterial({ color: 0x515151 });
const cube = new THREE.Mesh(geometry, fillMaterial);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffff00 });
const line = new THREE.LineSegments(
//new THREE.WireframeGeometry(geometry),
geometry,
lineMaterial
);
모델의 모든 외곽선이 표시되지 않는것을 볼 수 있다.
3. OrbitControls
현재 모델이 자동으로 회전하게 되어있는데 이를 제거하고
마우스로 조정가능하도록 변경해 보겠다
먼저 기존 회전시키는 부분을 주석처리해보자
update(time) {
time *= 0.001; // second unit
//this._cube.rotation.x = time; // 모델이 자동으로 회전
//this._cube.rotation.y = time;
}
다음 Orbitcontrols 을 import 해준다
import { OrbitControls } from "../examples/jsm/controls/OrbitControls.js";
가끔 ./ / 뭐 이런걸로 시작해야한다고 에러가 날때가 있다
그럴땐 html에 이게 추가되어있는지 확인해야함
{
"imports": {
"three": "../build/three.module.js"
}
}
위코드가 먹히지 않는다면
해당 라이브러리에 들어가서 three js 경로를 직접 지정해준다
그러고 나서
constructro()에 this._setupControls(); 메서드를 먼저 호출해준다
constructor() {
const divContainer = document.querySelector("#webgl-container");
this._divContainer = divContainer;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
divContainer.appendChild(renderer.domElement);
this._renderer = renderer;
const scene = new THREE.Scene();
this._scene = scene;
this._setupCamera();
this._setupLight();
this._setupModel();
this._setupControls();
window.onresize = this.resize.bind(this);
this.resize();
requestAnimationFrame(this.render.bind(this));
}
그리고 setupControls()메서드를 정의해보자
첫번째 인자로 시점을 조절할 카메라를 지정해주고,
두번째 인자로 마우스이벤트를 받을 DOM요소를 지정해 준다.
_setupControls() {
new OrbitControls(this._camera, this._divContainer);
}
이제 마우스로 시점을 움직일 수 있다
'웹 개발 > 🧊 ThreeJS' 카테고리의 다른 글
Three.js | Geometry - ConeGeometry (0) | 2024.05.06 |
---|---|
Three.js | Geometry - CircleGeometry (0) | 2024.05.06 |
Three.js | Geometry - BoxGeometry (0) | 2024.05.06 |
Three.js | 기본 구성 요소와 코드 (0) | 2024.05.06 |
Three.js | 개발환경구성 & 실행 (0) | 2024.05.05 |