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

인기 글

태그

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

최근 글

관리자

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

w__am 개발노트

Raycaster, 특정 방향의 광선(Ray)에 맞은 Mesh 판별하기
Frontend/Three.js

Raycaster, 특정 방향의 광선(Ray)에 맞은 Mesh 판별하기

2024. 11. 12. 22:55

 

(준비) Line으로 선 만들고 메쉬 배치하기

 

Geometry를 이용해 광선을 시각적으로 보기

레이캐스터에서 쏘는 광선은 눈에 보이지 않기 때문에 시각적으로 보이도록 광선과 동일한 위치에 geometry를 이용해 광선 그리면 된다.

 

 

  /* Mesh 만들기 : Geometry를 이용해 광선을 시각적으로 보기 */
  // 선의 시작점과 끝점을 정의
  const lineMaterial = new THREE.LineBasicMaterial({ color: "yellow" });
  const points = [];
  points.push(new THREE.Vector3(0, 0, 100)); // 모니터 바깥 방향 (화면에서 앞쪽)
  points.push(new THREE.Vector3(0, 0, -100)); // 모니터 안쪽 방향 (화면에서 뒤쪽)

  // 정해진 두 점을 잇는 형태
  const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);

  // 광선의 위치를 시각화 하기
  const guide = new THREE.Line(lineGeometry, lineMaterial);
  scene.add(guide);
  • BufferGeometry는 기본 geometry이며, 임의로 포인트를 설정할 수 있다.
  • 포인트를 이어주면서 geometry 형태를 만들어 선을 만들면 된다.

 

 

광선에 맞을 물체 생성

 // 광선에 맞을 물체 생성
  const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
  const boxMaterial = new THREE.MeshStandardMaterial({ color: "plum" });
  const boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
  boxMesh.name = "box";

  const torusGeometry = new THREE.TorusGeometry(2, 0.5, 16, 100);
  const torusMaterial = new THREE.MeshStandardMaterial({ color: "lime" });
  const torusMesh = new THREE.Mesh(torusGeometry, torusMaterial);
  torusMesh.name = "torus";
  scene.add(boxMesh, torusMesh);

  const meshes = [boxMesh, torusMesh]; 
  • boxMesh, torusMesh를 배열로 넣은 이유는 물체를 움직이게 하면서 광선에 맞았는지 체크할 때 배열에 넣어놔야 한 번에 체크하기가 편하다.

 

 

특정 광선을 지나는 메쉬 체크하기

 

Raycaster 만들기, 광선 세팅

  /* Raycaster 만들기 */
  const raycaster = new THREE.Raycaster();

  function draw() {
    /* Raycaster 세팅 */
    const origin = new THREE.Vector3(0, 0, 100); // 광선을 쏘는 출발점
    const direction = new THREE.Vector3(0, 0, -100); // 광선을 쏘는 뱡향
    direction.normalize(); // 정규화된 벡터로 변환해주는 함수
  
    raycaster.set(origin, direction);

    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
  }
  • 위치는 Vector3로 설정하면 된다.

 

  • THREE.Raycaster를 사용할 때, 방향 설정은 중요한 요소다.
    • 레이캐스터의 방향은 정규화된 벡터여야 한다.
    • 이는 벡터의 길이를 1로 맞추는 것을 의미한다.
    	const direction = new THREE.Vector3(0, 0, -100);
    	direction.normalize(); // 정규화된 벡터로 변환해주는 함수
    	console.log(direction.length()); // 1
    	// const direction = new THREE.Vector3(0, 0, -1);과 동일한 코드가 된다.
    

 

  • const origin = new THREE.Vector3(0, 0, 100); // 광선을 쏘는 출발점
    • 광선의 출발점은 모니터 바깥 방향과 동일한 위치로 설정하면 된다.
    • points.push(new THREE.Vector3(0, 0, 100)); // 모니터 바깥 방향 (화면에서 앞쪽)

 

  • const direction = new THREE.Vector3(0, 0, -1); // 광선을 쏘는 뱡향
    • 광선의 방향은 모니터 안쪽 방향과 동일한 위치로 설정하면 된다.
    • 단, 정규화된 벡터여야 한다.
    • points.push(new THREE.Vector3(0, 0, -100)); // 모니터 안쪽 방향 (화면에서 뒤쪽)
    • 크기와 상관없이 방향만 같다면 동일한 방향으로 인식되므로, new THREE.Vector3(0, 0, -1)처럼 길이 1인 벡터로 설정해도 방향은 동일하다.

 

 

Raycaster 만들기, 특정 광선을 지나는 메쉬 체크하기

  /* Raycaster 만들기 */
  const raycaster = new THREE.Raycaster();

  function draw() {
       /* Raycaster 세팅 */
    const origin = new THREE.Vector3(0, 0, 100); // 광선을 쏘는 출발점
    const direction = new THREE.Vector3(0, 0, -1); // 광선을 쏘는 뱡향
    raycaster.set(origin, direction);

    // 특정 광선을 지나는 Mesh 체크하기
    const intersects = raycaster.intersectObjects(meshes);
    intersects.forEach((item) => {
      console.log(item.object.name);
    });

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

intersectObjects을 map을 돌린 이유

  • const intersects = raycaster.intersectObjects(meshes);
  • 광선에 박스만 맞았는데 결과 값이 2개 나오는이유
  • 박스의 앞면과 뒷면이 맞아서 광선에서 2개를 지났다 체크 된 것
  • 각 mesh 이름을 지정해주고 mesh 이름으로 광선이 지나갔는지 체크하면 된다.

 

 

Raycaster 만들기, 물체 애니메이션 추가 + 광선이 관통하면 색상이 변경되도록 설정

  /* Raycaster 만들기 */
  const raycaster = new THREE.Raycaster();

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

  function draw() {
    const time = clock.getElapsedTime();

    boxMesh.position.y = Math.sin(time) * 2;
    torusMesh.position.y = Math.cos(time) * 2;
    
    // 기본 색상 설정, 광선이 관통하지 않았을 때
    boxMesh.material.color.set("plum");
    torusMesh.material.color.set("lime");

    /* Raycaster 세팅 */
    const origin = new THREE.Vector3(0, 0, 100); // 광선을 쏘는 출발점
    const direction = new THREE.Vector3(0, 0, -1); // 광선을 쏘는 뱡향
    raycaster.set(origin, direction);

    // 특정 광선을 지나는 Mesh 체크하기
    const intersects = raycaster.intersectObjects(meshes);
    intersects.forEach((item) => {
      // 광선이 관통하면 색상이 변경되도록 설정
      item.object.material.color.set("red");
    });

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

 

 

 

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

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

Raycaster, 드래그 클릭 방지  (0) 2024.11.25
Raycaster, 클릭한 Mesh 감지하기  (0) 2024.11.14
Raycaster, 동작 원리  (0) 2024.11.12
조명, RectAreaLight_직사각형 모양으로 균일한 빛을 방사하는 조명 효과  (0) 2024.11.11
조명, HemisphereLight_하늘과 땅을 기반으로 빛을 조절하는 조명 효과  (0) 2024.11.11
    'Frontend/Three.js' 카테고리의 다른 글
    • Raycaster, 드래그 클릭 방지
    • Raycaster, 클릭한 Mesh 감지하기
    • Raycaster, 동작 원리
    • 조명, RectAreaLight_직사각형 모양으로 균일한 빛을 방사하는 조명 효과
    wam
    wam

    티스토리툴바