wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • 원형적인 움직임
  • Interface
  • 함수의 범위
  • 스코프
  • mapped types
  • 함수 표현식
  • type-graphql
  • getelapsedtime()
  • Decorators
  • axeshelper
  • 데이터 포맷
  • math.sin()
  • 삼각함수
  • 함수 리터럴
  • joi 에러
  • 디자인 패턴
  • math.cos()
  • reactive variables
  • getdelta()
  • gridhelper
  • 오프-프레미스(off-premise) 방식
  • API
  • isabstract
  • 함수 선언문
  • 렌더링 성능 최적화
  • e.preventdefault()
  • 초기 환경설정
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • three.js 구성 요소
  • react 성능 최적화

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

카메라 컨트롤, TrackballControls
Frontend/Three.js

카메라 컨트롤, TrackballControls

2024. 9. 4. 16:24

 

TrackballControls

 

import

import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
  • Three.js 라이브러리에서 사용되는 입력 컨트롤 중 하나로, 웹에서 3D 그래픽을 다루기 위한 자바스크립트 라이브러리이다.
  • 사용자가 3D 장면을 자유롭게 회전, 확대/축소, 그리고 이동하면서 조작할 수 있다.
  • 마우스 드래그, 휠 스크롤 등을 통해 직관적으로 3D 환경을 탐색할 수 있도록 도와준다.

 

 

import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";

/* 주제: TrackballControls */

export default function example() {
  /* Renderer 만들기 : html에 캔버스 미리 만들기 */
  const canvas = document.querySelector("#three-canvas");
  const renderer = new THREE.WebGLRenderer({
    canvas,
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);

  /* Scene 만들기 */
  const scene = new THREE.Scene();

  /* Camera 만들기 */
  const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.y = 1.5;
  camera.position.z = 7;
  scene.add(camera);

  /* Light 만들기 */
  const ambientLight = new THREE.AmbientLight("white", 0.5);
  scene.add(ambientLight);

  const directionalLight = new THREE.DirectionalLight("white", 1);
  directionalLight.position.x = 1;
  directionalLight.position.z = 2;
  scene.add(directionalLight);

  /* Controls 만들기 */
  const controls = new TrackballControls(camera, renderer.domElement); // 마우스를 이용해  3D 객체를 회전, 확대, 축소 가능
  controls.maxDistance = 20;
  controls.minDistance = 5;
  // controls.target.set(3, 3, 3);

  /* Messh 만들기 */
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  let mesh;
  let material;

  const minColorValue = 50; // RGB 값의 최소값
  const colorRange = 255 - minColorValue; // RGB 값의 범위 (최대값 - 최소값)
  for (let i = 0; i < 20; i++) {
    material = new THREE.MeshStandardMaterial({
      color: `rgb(
				${minColorValue + Math.floor(Math.random() * colorRange)},
				${minColorValue + Math.floor(Math.random() * colorRange)},
				${minColorValue + Math.floor(Math.random() * colorRange)}
			)`
    });

    // Mesh 무작위 위치 조정
    const range = 0.5;
    const positionRange = 5;
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.x = (Math.random() - range) * positionRange;
    mesh.position.y = (Math.random() - range) * positionRange;
    mesh.position.z = (Math.random() - range) * positionRange;
    scene.add(mesh);
  }

  /* 그리기 */
  const clock = new THREE.Clock();

  function draw() {
    const delta = clock.getDelta();

    // 매 번 반복 실행하는 draw함수에서 controls 업데이트 메서드를 매 번 실행해줘야 한다.
    // 작성하지 않으면 동작 모두 불가능
    controls.update();

    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
  }

  function setSize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.render(scene, camera);
  }

  /* 이벤트 */
  window.addEventListener("resize", setSize);

  draw();
}

  • 애니메이션 루프에서 controls.update()를 해주지 않으면 orbitControls와 다르게 동작하지 않는다.
  • orbitControls에서 update()를 해주지 않아도 회전이 가능했고 자동 회전이 되지 않았다.
  • 기본적으로 부드럽게 회전되는 enableDamping이 적용되어 있다.

 

 

 

저작자표시 변경금지 (새창열림)

'Frontend > Three.js' 카테고리의 다른 글

카메라 컨트롤, FlyControls  (0) 2024.09.04
카메라 컨트롤, OrbitControls와 TrackballControls 차이  (0) 2024.09.04
카메라 컨트롤, OrbitControls  (0) 2024.09.03
Geometry 형태 조작하기  (0) 2024.08.31
여러가지 Geometry 살펴보기  (0) 2024.08.29
    'Frontend/Three.js' 카테고리의 다른 글
    • 카메라 컨트롤, FlyControls
    • 카메라 컨트롤, OrbitControls와 TrackballControls 차이
    • 카메라 컨트롤, OrbitControls
    • Geometry 형태 조작하기
    wam
    wam

    티스토리툴바