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

인기 글

태그

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

최근 글

관리자

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

w__am 개발노트

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

카메라 컨트롤, DragControls

2024. 9. 5. 18:37

 

DragControls

 

3D 장면에서 마우스를 사용해 오브젝트를 드래그하고 이동할 수 있도록 해주는 컨트롤이다. 사용자가 화면에서 직접적으로 물체를 선택하고 조작할 수 있게 해준다.

 

 

이 컨트롤러는 Raycaster를 사용해 마우스 포인터와 3D 공간에서의 오브젝트 간 교차를 감지하고, 선택된 오브젝트를 드래그하는 기능을 제공한다.

 

 

드래그 시작시 발광 색상 적용 및 복구

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

/* 주제: DragControls */

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);

  /* Messh 만들기 */
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  let mesh;
  let material;
  const meshes = []; // 씬에 드래그할 수 있는 오브젝트 추가

  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;
    mesh.name = `box-${i}`; // 각 box의 이름 지정
    scene.add(mesh);
    meshes.push(mesh);
  }

  /* Controls 만들기 */
  // 코드 위치 중요, meshes 배열이 정의된 후 작성해야 한다.
  const controls = new DragControls(meshes, camera, renderer.domElement);

  // 드래그 시작 시 호출되는 이벤트
  controls.addEventListener("dragstart", (e) => {
    console.log("드래그 시작", e.object.name);
    e.object.userData.originalColor = e.object.material.color.clone(); // 원래 색상 저장
    e.object.material.emissive.setRGB(0.5, 0.5, 0.5); // 드래그 시작하면 발광 색상 적용
  });

  // 드래그 종료 시 호출되는 이벤트
  controls.addEventListener("dragend", (e) => {
    console.log("드래그 종료", e.object.name);
    e.object.material.emissive.set(0x000000); // 발광 색상 초기화
    e.object.material.color.copy(e.object.userData.originalColor); // 원래 색상 복구
  });

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

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

    // DragControls에는 업데이트 메소드가 없다.

    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();
}

 

 

Constructor

DragControls( objects : Array, camera : Camera, domElement : HTMLDOMElement )

objects : 드래그 가능한 3D 오브젝트 배열

camera : 렌더링된 장면의 카메라.

domElement : 이벤트 리스너에게 사용되는 HTML 요소

 

 

주요 기능

 

  1. 마우스로 오브젝트 선택 및 드래그
    • 사용자가 마우스를 클릭하여 특정 오브젝트를 선택하고, 마우스 이동에 따라 오브젝트를 화면 내에서 이동할 수 있다.

  2. 여러 개의 오브젝트 드래그
    • 하나 이상의 오브젝트를 동시에 선택하고 드래그할 수 있다.

  3. 이벤트 리스너 제공
    • 드래그 시작, 드래그 중, 드래그 종료 등 다양한 이벤트를 처리할 수 있는 기능을 제공해준다.

 

 

주요 메서드와 이벤트

  • enabled
    • true일 때 드래그가 활성화
    • false로 설정하면 드래그 기능을 비활성


  • addEventListener(type, listener) 이벤트에 대한 리스너를 등록할 수 있다.
    • 드래그 시작(dragstart)
    • 드래그 중(drag)
    • 드래그 종료(dragend)


  • removeEventListener(type, listener)
    • 등록된 이벤트 리스너를 제거

 

 

발광 색상 복사 및 복구

 

emissive는 발광 색상을 정의하는 것

 

clone(): 객체 자체를 복사 (색상 객체의 깊은 복사)

e.object.userData.originalColor = e.object.material.color.clone();
  • clone()은 기존의 THREE.Color 객체를 깊은 복사하여 완전히 새로운 THREE.Color 객체를 만든다.
  • clone()을 사용함으로써 material.color가 바뀌더라도 originalColor가 영향을 받지 않게 된다. 즉, 두 개의 독립적인 THREE.Color 객체가 생성된다.

 

 

copy():색상 값을 복사

 e.object.material.color.copy(e.object.userData.originalColor);
  • copy()는 originalColor 객체의 색상 값을 현재의 material.color에 복사해 넣는 역할을 한다.
  • 드래그가 종료되었을 때, 저장해 둔 원래 색상으로 되돌리기 위해 copy()를 사용해 값만 복사한다. 이때 copy()는 객체 자체를 복사하지 않고, 그 객체 안에 있는 색상 값만을 복사한다.

 

 

요약

 

clone()

  • 새로운 THREE.Color 객체를 생성해 독립적인 객체로 만든다.
  • 이 객체는 원래 객체와는 분리되어 값이 변경되지 않는다.

 

 

copy()

  • 기존 객체(material.color)의 값만 복사하여 원래 색상으로 되돌린다.
  • 이는 객체를 새로 만드는 것이 아니라 값만 덮어쓰는 방식이다.

 

 

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

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

재질, MeshBasicMaterial  (0) 2024.09.30
카메라 컨트롤, Minecraft Controls  (0) 2024.09.05
카메라 컨트롤, PointerLockControls  (0) 2024.09.05
카메라 컨트롤, FirstPersonControls  (0) 2024.09.05
카메라 컨트롤, FlyControls  (0) 2024.09.04
    'Frontend/Three.js' 카테고리의 다른 글
    • 재질, MeshBasicMaterial
    • 카메라 컨트롤, Minecraft Controls
    • 카메라 컨트롤, PointerLockControls
    • 카메라 컨트롤, FirstPersonControls
    wam
    wam

    티스토리툴바